Integrate "react-intl" langage locale with switcher in storybook

129 Views Asked by At

I am trying to include langage locale support from my React components in Storybook using "react-intl", I added the following global types in "preview.js" as list of Languages supported to appear in the Storybook toolbar:

export const globalTypes = {
locale: {
    title: 'Locale',
    description: 'Internationalization locale',
    toolbar: {
      icon: 'globe',
      items: [
        { value: 'en', right: '', title: 'English' },
        { value: 'de', right: '', title: 'Deutsch' },
      ],
      dynamicTitle: true,
    },
  },
 };

When I switch the langages it does not work always the default langage is showed, I need to know the code that can be used to implement the langage switcher and make it work with the code implemented within our React application in IdwIntlProvider.. I have to implement the functionality without using the react-intl Addon.

1

There are 1 best solutions below

0
On

Add the selected locale in a decorator

import en from "../translations/en.json";
import fr from "../translations/fr.json";

// get the selected messages (json) for the locale
const getLanguage = (locale: string) => {
  switch (locale) {
    case 'en':
      return en;
    case 'fr':
      return fr;
    default:
      return fr;
  }
}

const preview: Preview = {
  // ...,
  decorators: [
    (Story, context) => {
      return (
        <NextIntlClientProvider locale={context.globals.locale} messages={getLanguage(context.globals.locale)}>
            {/*  Decorators in Storybook also accept a function. Replace <Story/> with Story() to enable it  */}
            <Story />
        </NextIntlClientProvider>
      );
    },
  ],
  globalTypes: {
    locale: {
      description: 'Global language for components',
      defaultValue: 'fr',
      toolbar: {
        // The label to show for this toolbar item
        title: 'Language',
        icon: 'globe',
        // Array of plain string values or MenuItem shape (see below)
        items: ['fr', 'en'],
        // Change title based on selected value
        dynamicTitle: true,
      },
    },
  // ...,
};