React-i18n Storybook Examples

6 min read Oct 14, 2024
React-i18n Storybook Examples

Integrating Internationalization (i18n) into Your React Storybook: A Practical Guide

Developing a React application that caters to a global audience requires careful consideration of internationalization (i18n). This ensures your application can be easily adapted to different languages and regional settings. Storybook, a popular tool for developing and testing UI components in isolation, can be seamlessly integrated with i18n solutions to provide localized previews of your components.

Why Use Storybook for React i18n?

Storybook is invaluable for creating a consistent and efficient workflow for i18n in your React application. Here's why:

  • Isolated Testing: Storybook allows you to preview individual components in isolation, simplifying the process of testing language translations.
  • Interactive Development: You can interactively switch between languages within Storybook, facilitating a seamless workflow for language testing and debugging.
  • Documentation and Collaboration: Storybook serves as a living documentation of your components and their localized variations, fostering seamless collaboration among developers and translators.

Popular i18n Libraries for React

Several powerful i18n libraries are available for React, each offering its own strengths and features. Here are some of the most widely used:

  • react-i18next: A popular and feature-rich library known for its flexibility, performance, and robust community support.
  • i18n-react: A lightweight and easy-to-use library that provides a simple and straightforward way to implement i18n in your React projects.
  • lingui: A popular i18n solution that emphasizes code simplicity and developer experience, offering a streamlined workflow for translations.

Setting up React i18n in Storybook: A Practical Example

Let's illustrate the integration of react-i18next into Storybook with a practical example.

1. Project Setup:

  • Create a new React project using Create React App: npx create-react-app my-i18n-app
  • Install the necessary dependencies:
    npm install react-i18next i18next react-i18next-http-backend @storybook/addon-actions @storybook/addon-essentials @storybook/addon-links
    

2. Configure React i18next:

  • Create a i18n.js file in your src directory:
    import i18n from 'i18next';
    import { initReactI18next } from 'react-i18next';
    import HttpApi from 'i18next-http-backend';
    
    i18n
      .use(initReactI18next)
      .use(HttpApi)
      .init({
        resources: {
          en: {
            translation: {
              'hello': 'Hello world!',
              'button': 'Click me'
            }
          },
          fr: {
            translation: {
              'hello': 'Bonjour le monde!',
              'button': 'Cliquez-moi'
            }
          }
        },
        lng: 'en', // Default language
        fallbackLng: 'en', // Fallback language
        backend: {
          loadPath: '/locales/{{lng}}/{{ns}}.json', // Path to your translation files
        },
      });
    
    export default i18n;
    

3. Create Your React Component:

  • Create a simple component MyComponent.jsx:
    import React from 'react';
    import { useTranslation } from 'react-i18next';
    
    const MyComponent = () => {
      const { t } = useTranslation();
    
      return (
        

    {t('hello')}

    ); }; export default MyComponent;

4. Configure Storybook:

  • Create a main.js file in your .storybook directory:
    import React from 'react';
    import { addDecorator, addParameters } from '@storybook/react';
    import { withKnobs } from '@storybook/addon-knobs';
    import i18n from '../src/i18n';
    import { I18nextProvider } from 'react-i18next';
    
    addDecorator((storyFn) => (
      
        {storyFn()}
      
    ));
    
    addParameters({
      actions: { argTypesRegex: '^on[A-Z].*' },
      controls: {
        matchers: {
          color: /(background|color)$/i,
          date: /Date$/,
        },
      },
    });
    
    addDecorator(withKnobs);
    

5. Create Storybook Stories:

  • Create a MyComponent.stories.js file in your src/stories directory:
    import MyComponent from '../MyComponent';
    
    export default {
      title: 'MyComponent',
      component: MyComponent,
    };
    
    const Template = (args) => ;
    
    export const Default = Template.bind({});
    Default.args = {};
    
    export const French = Template.bind({});
    French.args = { lng: 'fr' };
    

6. Run Storybook:

  • Start Storybook: npm run storybook

Now you can access your Storybook and view your component in different languages by switching the lng parameter in the French story. You can even add more languages to your i18n.js file and create corresponding stories for them.

Conclusion

Integrating react-i18next into Storybook simplifies the process of building and testing localized components. By following the steps outlined above, you can ensure your React application is accessible and engaging for a global audience. Storybook provides a powerful tool for developing, testing, and documenting your i18n efforts, leading to a more efficient and collaborative development process.

Featured Posts