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>
));
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;
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"
}
}
Top comments (9)
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
Yes, I'm using the
useTranslation()
hook.Ruben did you ever solve this issue?
We are using this in main.js:
thanks
this is a ssr language load?
I believe it's a client-side load inside of Storybook.
As specified in the documentation of react-i18-next you have to add
.use(Backend)
.You've saved me some hours. Thanks for the post! :)