1

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?

1 Answer 1

2

You need to pass the switchLang function:

<Provider value={{currentLan: this.state.currentLan, switchLang}}>{this.props.children}</Provider>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.