Monday, 30 July 2018

How to update React Context from inside a child component?

I have the language settings in the context as like below

class LanguageProvider extends Component {
  static childContextTypes = {
    langConfig: PropTypes.object,
  };

  getChildContext() {
    return { langConfig: 'en' };
  }

  render() {
    return this.props.children;
  }
}

export default LanguageProvider;

My application code will be something like below

<LanguageProvider>
  <App>
    <MyPage />
  </App>
</LanguageProvider>

My Page is having a component to switch the language

<MyPage>
  <LanguageSwitcher/>
</MyPage>

LanguageSwitcher in this MyPage need to update the context to change the language into 'jp' as below

class LanguageSwitcher extends Component {
  static contextTypes = {
    langConfig: PropTypes.object,
  };

  updateLanguage() {
    //Here I need to update the langConfig to 'jp' 
  }

  render() {
    return <button onClick={this.updateLanguage}>Change Language</button>;
  }
}

export default LanguageSwitcher;

How can I update the context from inside the LanguageSwitcher component ?



from How to update React Context from inside a child component?

No comments:

Post a Comment