wiziple / gatsby-plugin-intl

Gatsby plugin that turns your website into an internationalization-framework out of the box.
http://gatsby-starter-default-intl.netlify.com
325 stars 178 forks source link

How to use with Storybook? #175

Open jdahdah opened 3 years ago

jdahdah commented 3 years ago

Does anyone by chance have a working example of how to use this with Storybook? Some of my components use <FormattedMessage /> and <Link /> from gatsby-plugin-intl, and I'm not sure how to get those working within the Storybook context.

I tried adding context providers like <IntlProvider /> and <IntlContextProvider /> to a story, but they rely on pageContext, which is not available outside of the gatsby runtime environment.

bud-mo commented 3 years ago

Hi @jdahdah I got the <FormattedMessage /> and <Link /> components working.

file: .storybook/wrap-with-provider.js

import React from 'react';
import { IntlProvider, IntlContextProvider} from 'gatsby-plugin-intl';
import messages from '../src/intl/en.json';
import { createIntl, createIntlCache } from 'react-intl';

const intlCache = createIntlCache();
const intl = createIntl(
  {
    defaultLanguage: 'en',
    language: 'en',
    messages: messages,
  },
  intlCache,
);

export default function WrapWithProvider(Story) {
  return (
    <IntlProvider
      locale={intl.language}
      defaultLocale={intl.defaultLanguage}
      messages={intl.messages}
    >
      <IntlContextProvider
        value={intl}
      >
          <Story />
      </IntlContextProvider>
    </IntlProvider>
  );
}

File: .storybook/preview.js

import WrapWithProvider from './wrap-with-provider';

export const decorators = [
  WrapWithProvider,
];
bud-mo commented 3 years ago

@jdahdah More or less, the wrapPage function from gatsby-plugin-intl does the same thing.

jdahdah commented 3 years ago

@bud-mo Amazing, I will give this a shot next week and let you know how it goes. Thank you for sharing!