gatsby-plugin-intl icon indicating copy to clipboard operation
gatsby-plugin-intl copied to clipboard

How to use with Storybook?

Open jdahdah opened this issue 4 years ago • 3 comments

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.

jdahdah avatar Mar 18 '21 12:03 jdahdah

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 avatar Sep 10 '21 11:09 bud-mo

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

bud-mo avatar Sep 10 '21 16:09 bud-mo

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

jdahdah avatar Sep 10 '21 17:09 jdahdah