React-i18next: Dynamically update ns prop on I18n component

Created on 21 Sep 2018  路  6Comments  路  Source: i18next/react-i18next

Hey @jamuhl,

while experimenting with different options to work around #519, I discovered that it is not possible to dynamically update namespaces passed to I18n. It only adds namespaces once in componentDidMount which breaks the use case below:

class App extends React.Component {
  state = { ns: [] };

  addNs = ns => this.setState(prev => { ns: [...prev.ns, ns] });

  render() {
    return (
      <I18n ns={this.state.ns}>
        {t => <Admin addNs={this.addNs} t={t} />}
      </I18n>
    );
  };
}

class Admin extends React.Component {
  componentDidMount() {
    this.props.addNs("admin");
  }

  ...
}

I played around with updating the key prop on I18n whenever the namespaces change. That forces a re-mount and sort of does what it's supposed to. But throwing away and re-mounting I18n and its potentially huge tree of descendants isn't really a solution 馃檲

Do you think calling i18n.loadNamespaces() in I18n's componentDidUpdate might be a reasonable and feasible fix (which perhaps wouldn't require a breaking change)?

Thanks again!
Nicolas

All 6 comments

the problem with the adding namespaces dynamically after initial mount - the component has one role which is to suspend rendering while loading translations - so adding namespaces later it would go from a ready state back to a not ready -> rendering null again...

@jamuhl, ha okay, I didn't consider the wait option. I've experimented with loading namespaces in componentDidUpdate but it doesn't block rendering on subsequent rerenders in case the translations aren't available yet. It seems to work for my specific use case but might be problematic in general (?). Let me know if you still see a chance to get something like that merged. Otherwise, feel free to close the issue!

Thanks for your support!

We might add this. Just with some extra documented hint that it will not work with the wait flag (once the hoc triggers ready it won't change back because of newly added namespaces to load). So it will be useful for cases like yours - but not overall.

If you like you might submit a PR.

Great, sounds good! I tried my best with these two PRs:

Please let me know if there's anything else I can do! @jamuhl

looks solid...give me some time to look through it, merging and publishing an update.

thanks a lot for taking the time to set this up...

published in [email protected]

Was this page helpful?
0 / 5 - 0 ratings