goooseman / storybook-addon-i18n

Storybook I18n Addon can be used to change locale of the component inside the preview in storybook
34 stars 3 forks source link

How do I know which locale is currently selected? #2

Closed thedanheller closed 5 years ago

thedanheller commented 5 years ago

In order to get messages, I need the currently selected locale. How do I get its context?

goooseman commented 5 years ago

storybook-addon-i18n is written intl library agnostic, so it can be complex to use it with different intl providers.

For example, we are using lioness library to do the internalization on our frontend.

lioness has a build-in provider, which have locale and messages props. Messages are in the following format:

type Messages = {
  [locale: string]: LocaleObject
}

So lioness receives the full object of all locales and chooses the needed one with a locale key.

In your case maybe the provider from your intl library needs not the object of messages for all locales, but the object of messages for one locale only.

But in this case you can build your own wrapper in a following way:

export class LocaleProvider extends React.PureComponent {
  public render() {
    const { locale, direction, messages } = this.props;
    return (
      <YourIntlLibraryProvider locale={locale} messages={messages[locale]}>
          {this.props.children}
      </YourIntlLibraryProvider>
    );
  }
}

And use this wrapper inside your storybook, providing messages as an object of different locales.