Reactjs Context Provider Error
I'm getting the following error
invariant.js:42 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Here is my app.js
import React from 'react';
import ReactDOM from 'react-dom';
import { UserProvider } from "./lib/user.js"
const App = () => <UserProvider></UserProvider>
ReactDOM.render(
<App />,
document.getElementById("app")
);
and here is the ./lib/user.js
:
import React from 'react'
export const UserContext = React.createContext({
user: null,
logIn: ((token, user) => {}),
logOut: (() => {})
})
export class UserProvider extends React.Component {
constructor(props) {
super(props)
this.logIn = (token, user) => {
setToken(token)
this.setState(state => ({user: user}))
}
this.logOut = (client) => {
clearToken()
this.setState(state => ({user: null}))
client.resetStore()
client.cache.reset()
}
this.state = {
user: null,
logIn: this.logIn,
logOut: this.logOut
}
}
render() {
console.log(<div></div>)
console.log(<UserContext.Provider/>)
return (
<UserContext.Provider value={this.state}>
<p>hi</p>
</UserContext.Provider>
)
}
}
This is on React 16.3.2. There are many situations where the error is due to default vs named exports, which this is not appear to be:
To solve the error "Element type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got", make sure to import named exports using curly braces and default exports without, and only use functions or classes as components.
React. cloneElement() is part of the React Top-Level API used to manipulate elements. It clones and returns a new element using its first argument as the starting point. This argument can be a React element or a component that renders a React element.
React. createElement( type, [props], [... children] ) Create and return a new React element of the given type. The type argument can be either a tag name string (such as 'div' or 'span' ), a React component type (a class or a function), or a React fragment type.
The error "JSX element type does not have any construct or call signatures" occurs when we try to pass an element or a react component as props to another component but type the prop incorrectly. To solve the error, use the React. ElementType type.
You are probably using [email protected]
with an earlier react-dom
version (e.g. 16.2) that doesn't support context yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With