Add a language switcher to Storybook

· Tech

Do you want to add a language switcher to Storybook that looks like this?

Storybook - language switcher

It’s easy to do! Edit the .storybook/preview.ts file and add the following code:

.storybook/preview.ts
import { setLocale } from "@my-app/i18n"; // import a function to set the locale
import { Preview } from "@storybook/your-framework"; // import the Preview type for your framework
const preview: Preview = {
decorators: [
(story, context) => {
const { locale } = context.globals; // get the locale from the global context
setLocale(locale); // set the locale
return story();
},
],
};
export const globalTypes = {
locale: {
name: "Locale",
description: "Internationalization locale",
defaultValue: "en-GB",
toolbar: {
icon: "globe",
items: [
{ value: "de-DE", title: "German (Germany)" },
{ value: "en-GB", title: "English (United Kingdom)" },
{ value: "en-IE", title: "English (Ireland)" },
{ value: "en-US", title: "English (United States)" },
{ value: "pl-PL", title: "Polish (Poland)" },
],
showName: true,
},
},
};
export default preview;

This will add a language switcher to your Storybook toolbar. 🎉

You can read more about toolbars and globals in the official Storybook documentation.