I am trying to use the new ReactJs Context, as an alternative to Redux, however I am getting an error of.
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
https://reactjs.org/docs/context.html
Here is the code for my layout which I have wrapped in the MyProvider tag
import React, { Component } from "react";
import { NavMenu } from "./NavMenu";
import { MyProvider } from "../contexts/context";
export class Layout extends Component {
render() {
return (
<MyProvider>
<div className="container-fluid">
<div className="row">
<div className="col-sm-3">
<NavMenu />
</div>
<div className="col-sm-9">
{this.props.children}
</div>
</div>
</div>
</MyProvider>
);
}
}
Here is the context code which I am importing
import React, { Component } from "react";
export const MyContext = React.createContext();
export class MyProvider extends Component {
state = {
name: 'test name'
}
render() {
return (
<MyContext.Provider value="{this.state}">
{this.props.children}
</MyContext.Provider>
)
}
}
Here is the place the provider is being consumed
import React, { Component } from "react";
import { RouteComponentProps } from "react-router";
import { MyProvider } from "../contexts/context";
export class Counter extends Component {
render() {
return <div className="m-2">
<MyContext.Consumer>
{(c) => (<p>My name is {c.state.name}</p>)}
</MyContext.Consumer>
</div>;
}
}
any help would be greatly appreciated.
NavMenuexported correctly? Can you please show the code of it?MyProvider.Consumer.MyProvideris the output ofReact.createContext()so not a valid React element by itselfMyProvideris the react component. The naming is really confusing here.MyContextis the output ofReact.createContext(). @user3284707 You should fix this.