DEV Community

Justin
Justin

Posted on

Using next-i18next in Storybook

next-i18next is built to work server-side as well as client-side. Storybook doesn't support server-side rendering so there's nowhere to add the next-i18next middleware. The good news is that means we don't have to support server-side rendering and can just use the underlying react-i18next and i18next-instance.

Adding a Storybook Decorator

We're going to add a decorator which will allow us wrap all stories in the <I18nextProvider>.

The decorator will be added to .storybook/preview.js so you need to create one if you haven't already.

import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';

addDecorator(storyFn => (
  <I18nextProvider i18n={i18n}>{storyFn()}</I18nextProvider>
));
Enter fullscreen mode Exit fullscreen mode

Configuring i18next

We can't use the same i18n config that we use in next-i18next. We need to use a react-i18next instance. I recommend creating the file at .storybook/i18n.js since it's just for Storybook config. The setup can be as simple as this:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n.use(initReactI18next).init({
  fallbackLng: 'en',
  debug: true
});

export default i18n;
Enter fullscreen mode Exit fullscreen mode

Configuring Static Paths in Storybook

The last step is to tell Storybook that it should serve the locales dir as a static path. We achieve this with the -s CLI flag.

{
  "scripts": {
    "start-storybook": "start-storybook -s ./public"
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (9)

Collapse
 
rbgoncalves profile image
Rúben Gonçalves

Aren't you using "useTranslation" hook right? Because I've the same setup but what fails is my component using "useTranslation" hook from next-i18next instead of the one from react-i18next

Collapse
 
justincy profile image
Justin

Yes, I'm using the useTranslation() hook.

Collapse
 
ckeeney profile image
CJ Keeney

Ruben did you ever solve this issue?

Collapse
 
will0684 profile image
Jordan Willis

We are using this in main.js:

config.resolve.alias = {
  ...config.resolve.alias,
  'next-i18next': 'react-i18next'
}
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
tadjerounimohamedadel profile image
Adel Mohamed Tadjerouni

thanks

Collapse
 
iconic0 profile image
iCONIC0

this is a ssr language load?

Collapse
 
justincy profile image
Justin

I believe it's a client-side load inside of Storybook.

Collapse
 
elbalexandre profile image
Alexandre Nicolas

As specified in the documentation of react-i18-next you have to add .use(Backend).

Collapse
 
andfk profile image
Andrés F

You've saved me some hours. Thanks for the post! :)