I am working on a React JS project that uses the context API, React hooks and the functional components. Now. I am trying to create a context provider and trying to change the state if its from the child component. But it is not working as expected. This is what I have done so far.
I have created context provider component with the following definition.
import React, { Component } from 'react';
const { Provider, Consumer } = React.createContext({ currentLan: 'en' });
class LangContextProvider extends Component {
state = {
currentLan: 'en'
}
switchLang = () => {
this.setState({
currentLan: this.state.currentLan == 'it'? 'en': 'it',
})
}
render() {
return <Provider value={this.state}>{this.props.children}</Provider>
}
}
export { LangContextProvider, Consumer as LangContextConsumer };
Pay attention to the switchLang
function, because I am trying to call it from the child component to update the state.
This is my child component with a button that updates the state of the provider.
const SwitchLangButton = () => {
return (
<LangContextConsumer>
{langContext => (
<button onClick=() => { langContext.switchLang() }>Switch lang</button>)
}
</LangContextConsumer>
)
}
As you can see, I am calling switchLang
function when the button is click to switch language.
I wrap my app with the provider as follow.
<LangContextProvider>
<React.Fragment>
<App />
</React.Fragment>
</LangContextProvider>
When I click on the button, I got the following error.
Uncaught TypeError: langContext.switchLang is not a function
What is wrong with my code?
You need to pass the switchLang function: