Search code examples
javascriptreactjsinternationalizationreact-intl

Dynamically change locale without redux


I was wondering if it was possible to dynamically change the locale and have the app rerender without using redux.

ReactDOM.render(
<IntlProvider locale={window.locale} messages={window.messages} >
    <Router history={history}>
        <App /> 
    </Router>
</IntlProvider>,
document.getElementById('root'));
registerServiceWorker();

Solution

  • You could have container component above IntlProvider and pass locale as a prop. But I imagine that would be very tedious to pass down the component tree:

    class Container extends React.Component {
      state: {
        locale: window.locale
      }
    
      changeLocale = (locale) => this.setState({ locale })
    
      render() {
        return (
          <IntlProvider locale={this.state.locale} messages={window.messages} >
            <Router history={history}>
              <App changeLocale={this.changeLocale} /> 
            </Router>
          </IntlProvider>,
        )
      }
    }