I am using React Context api to pass some states to different child components and it's returning undefined
.
Parent component:
export const UserContext = React.createContext();
export class Provider extends Component {
state = {
editGroup: false,
}
render() {
return (
<UserContext.Provider value={{
state: this.state
}}>
{this.props.children}
</UserContext.Provider>
)
}
}
Child component:
import { UserContext } from './index';
return (
<React.Fragment>
<UserContext.Consumer>
{(context) => (
<p>im inside the consumer {console.log(context)}</p>
)}
</UserContext.Consumer>
</React.Fragment>
);
This last console.log
is returning as undefined
, what am I doing wrong here ?
Also, make sure to pass context in the constructor if you override it!
export default class Profile extends React.Component {
static contextType = AuthContext;
// make sure you pass the context along to super!
constructor(props, context) {
super(props, context);
...
}
}
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