Skip to content

storybookjs/react-native

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Storybook for React Native

Important

This readme is in the process of being updated for v8 which is not yet released to stable, for v7 docs see the v7.6 docs.

With Storybook for React Native you can design and develop individual React Native components without running your app.

This readme is for the 8.3.1 version, you can find the 7.6 docs here.

If you are migrating from 7.6 to 8.3 you can find the migration guide here

For more information about storybook visit: storybook.js.org

Note

@storybook/react-native requires atleast 8.3.1, if you install other storybook core packages they should be ^8.3.1 or newer.

picture of storybook

Table of contents

Getting Started

New project

There is some project boilerplate with @storybook/react-native and @storybook/addon-react-native-web both already configured with a simple example.

For expo you can use this template with the following command

# With NPM
npx create-expo-app --template expo-template-storybook AwesomeStorybook

For react native cli you can use this template

npx react-native init MyApp --template react-native-template-storybook

Existing project

Run init to setup your project with all the dependencies and configuration files:

npx storybook@latest init

The only thing left to do is return Storybook's UI in your app entry point (such as App.tsx) like this:

export { default } from './.storybook';

Then wrap your metro config with the withStorybook function as seen below

If you want to be able to swap easily between storybook and your app, have a look at this blog post

If you want to add everything yourself check out the the manual guide here.

Additional steps: Update your metro config

We require the unstable_allowRequireContext transformer option to enable dynamic story imports based on the stories glob in main.ts. We can also call the storybook generate function from the metro config to automatically generate the storybook.requires.ts file when metro runs.

Expo

First create metro config file if you don't have it yet.

npx expo customize metro.config.js

Then wrap your config in the withStorybook function as seen below.

// metro.config.js
const path = require('path');
const { getDefaultConfig } = require('expo/metro-config');
const withStorybook = require('@storybook/react-native/metro/withStorybook');

/** @type {import('expo/metro-config').MetroConfig} */
const config = getDefaultConfig(__dirname);

module.exports = withStorybook(config, {
  // Set to false to remove storybook specific options
  // you can also use a env variable to set this
  enabled: true,
  // Path to your storybook config
  configPath: path.resolve(__dirname, './.storybook'),

  // Optional websockets configuration
  // Starts a websocket server on the specified port and host on metro start
  // websockets: {
  //   port: 7007,
  //   host: 'localhost',
  // },
});

React native

const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
const path = require('path');
const withStorybook = require('@storybook/react-native/metro/withStorybook');
const defaultConfig = getDefaultConfig(__dirname);

/**
 * Metro configuration
 * https://reactnative.dev/docs/metro
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {};
// set your own config here πŸ‘†

const finalConfig = mergeConfig(defaultConfig, config);

module.exports = withStorybook(finalConfig, {
  // Set to false to remove storybook specific options
  // you can also use a env variable to set this
  enabled: true,
  // Path to your storybook config
  configPath: path.resolve(__dirname, './.storybook'),

  // Optional websockets configuration
  // Starts a websocket server on the specified port and host on metro start
  // websockets: {
  //   port: 7007,
  //   host: 'localhost',
  // },
});

Writing stories

In storybook we use a syntax called CSF that looks like this:

import type { Meta, StoryObj } from '@storybook/react';
import { MyButton } from './Button';

const meta = {
  component: MyButton,
} satisfies Meta<typeof MyButton>;

export default meta;

type Story = StoryObj<typeof meta>;

export const Basic: Story = {
  args: {
    text: 'Hello World',
    color: 'purple',
  },
};

You should configure the path to your story files in the main.ts config file from the .storybook folder.

// .storybook/main.ts
import { StorybookConfig } from '@storybook/react-native';

const main: StorybookConfig = {
  stories: ['../components/**/*.stories.?(ts|tsx|js|jsx)'],
  addons: [],
};

export default main;

Decorators and Parameters

For stories you can add decorators and parameters on the default export or on a specifc story.

import type { Meta } from '@storybook/react';
import { Button } from './Button';

const meta = {
  title: 'Button',
  component: Button,
  decorators: [
    (Story) => (
      <View style={{ alignItems: 'center', justifyContent: 'center', flex: 1 }}>
        <Story />
      </View>
    ),
  ],
  parameters: {
    backgrounds: {
      values: [
        { name: 'red', value: '#f00' },
        { name: 'green', value: '#0f0' },
        { name: 'blue', value: '#00f' },
      ],
    },
  },
} satisfies Meta<typeof Button>;

export default meta;

For global decorators and parameters, you can add them to preview.tsx inside your .storybook folder.

// .storybook/preview.tsx
import type { Preview } from '@storybook/react';
import { withBackgrounds } from '@storybook/addon-ondevice-backgrounds';

const preview: Preview = {
  decorators: [
    withBackgrounds,
    (Story) => (
      <View style={{ flex: 1, color: 'blue' }}>
        <Story />
      </View>
    ),
  ],
  parameters: {
    backgrounds: {
      default: 'plain',
      values: [
        { name: 'plain', value: 'white' },
        { name: 'warm', value: 'hotpink' },
        { name: 'cool', value: 'deepskyblue' },
      ],
    },
  },
};

export default preview;

Addons

The cli will install some basic addons for you such as controls and actions. Ondevice addons are addons that can render with the device ui that you see on the phone.

Currently the addons available are:

Install each one you want to use and add them to the main.ts addons list as follows:

// .storybook/main.ts
import { StorybookConfig } from '@storybook/react-native';

const main: StorybookConfig = {
  // ... rest of config
  addons: [
    '@storybook/addon-ondevice-notes',
    '@storybook/addon-ondevice-controls',
    '@storybook/addon-ondevice-backgrounds',
    '@storybook/addon-ondevice-actions',
  ],
};

export default main;

Using the addons in your story

For details of each ondevice addon you can see the readme:

Hide/Show storybook

Storybook on react native is a normal React Native component that can be used or hidden anywhere in your RN application based on your own logic.

You can also create a separate app just for storybook that also works as a package for your visual components. Some have opted to toggle the storybook component by using a custom option in the react native developer menu.

getStorybookUI options

You can pass these parameters to getStorybookUI call in your storybook entry point:

{
    initialSelection?: string | Object (undefined)
        -- initialize storybook with a specific story.  eg: `mybutton--largebutton` or `{ kind: 'MyButton', name: 'LargeButton' }`
    storage?: Object (undefined)
        -- {getItem: (key: string) => Promise<string | null>;setItem: (key: string, value: string) => Promise<void>;}
        -- Custom storage to be used instead of AsyncStorage
    shouldPersistSelection: Boolean (true)
        -- Stores last selected story in your devices storage.
    onDeviceUI?: boolean;
        -- show the ondevice ui
    enableWebsockets?: boolean;
        -- enable websockets for the storybook ui
    query?: string;
        -- query params for the websocket connection
    host?: string;
        -- host for the websocket connection
    port?: number;
        -- port for the websocket connection
    secured?: boolean;
        -- use secured websockets
    shouldPersistSelection?: boolean;
        -- store the last selected story in the device's storage
    theme: Partial<Theme>;
        -- theme for the storybook ui
}

Using stories in unit tests

Storybook provides testing utilities that allow you to reuse your stories in external test environments, such as Jest. This way you can write unit tests easier and reuse the setup which is already done in Storybook, but in your unit tests. You can find more information about it in the portable stories section.

Contributing

We welcome contributions to Storybook!

  • πŸ“₯ Pull requests and 🌟 Stars are always welcome.
  • Read our contributing guide to get started, or find us on Discord and look for the react-native channel.

Looking for a first issue to tackle?

  • We tag issues with Good First Issue when we think they are well suited for people who are new to the codebase or OSS in general.
  • Talk to us, we'll find something to suits your skills and learning interest.

Examples

Here are some example projects to help you get started