How add react-relay component to the storybook?

by jasen_gottlieb , in category: Javascript , 2 months ago

How add react-relay component to the storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 2 months ago

@jasen_gottlieb 

To add a React Relay component to Storybook, you can follow these steps:

  1. Install Storybook and necessary addons:
1
2
npx -p @storybook/cli sb init
npm install --save-dev @storybook/addon-links @storybook/addon-actions


  1. Create a new story file for your Relay component (e.g. MyRelayComponent.stories.js) in the stories directory in your project:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';

import MyRelayComponent from '../components/MyRelayComponent';

storiesOf('MyRelayComponent', module)
  .add('default', () => (
    <MyRelayComponent
      onButtonClick={action('clicked')}
      onDataLoaded={data => console.log(data)}
    />
  ));


  1. Make sure your Relay component is properly configured with Relay and GraphQL. Update your component to use Relay as needed.
  2. Update your Storybook configuration in .storybook/config.js to include the Relay Environment Provider around your stories:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import React from 'react';
import { addDecorator } from '@storybook/react';
import { Environment, Network, RecordSource, Store } from 'relay-runtime';
import { RelayEnvironmentProvider } from 'react-relay';

const fetchQuery = async (operation, variables) => {
  // Implement your custom fetch function here
};

const environment = new Environment({
  network: Network.create(fetchQuery),
  store: new Store(new RecordSource()),
});

addDecorator(story => (
  <RelayEnvironmentProvider environment={environment}>
    {story()}
  </RelayEnvironmentProvider>
));


  1. Run Storybook and view your Relay component's story:
1
npm run storybook


Your Relay component should now be accessible within Storybook for development and testing purposes. Make sure to customize the setup according to your project's specific configuration and requirements.