How to get react-i18next to work with storybook?

Member

by larissa , in category: Javascript , 2 months ago

How to get react-i18next to work with storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 2 months ago

@larissa 

To get react-i18next to work with Storybook, you can follow these steps:

  1. Install the necessary dependencies by running the following command:
1
npm install i18next react-i18next --save


  1. Create a new folder named i18n in the src directory of your project.
  2. Within the i18n folder, create a new file named i18n.js and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n.use(initReactI18next).init({
  resources: {
    en: {
      translation: {
        // Add your English translations here
      }
    },
    // Add additional language translations as needed
  },
  fallbackLng: 'en',
  interpolation: {
    escapeValue: false
  }
});

export default i18n;


  1. Import and use the i18n.js file in your entry point file (e.g., index.js or App.js):
1
import './i18n/i18n';


  1. Start Storybook by running the following command:
1
npx start-storybook


  1. Create a new story file for your component (e.g., MyComponent.stories.js) and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import React from 'react';
import { withI18n } from '@storybook/addon-i18n';
import { withTranslation } from 'react-i18next';
import MyComponent from './MyComponent';

export default {
  title: 'MyComponent',
  decorators: [withI18n],
};

export const Default = () => <MyComponent />;


  1. Add translations for your component in the translation object within the i18n.js file.
  2. Use the useTranslation hook or withTranslation HOC in your components to access the translations.


By following these steps, you should be able to use react-i18next with Storybook in your project.