Using Storybook with React Native and React Native for Web

Mike Cripps
2 min readSep 3, 2020

--

Storybook is a great way to develop and test components in isolation and leveraging React Native for Web we can create React Native components and view them in a browser.

In this article we’ll be setting up a new project, creating a simple React Native component and viewing two stories. Note that this assumes a basic understanding of creating a React component.

1. Set up a new project

Run npm init in an empty folder to set up a new package.json file.

2. Add dependencies

Add the following dependencies.

npm i -S react react-native react-native-web @types/react @types/react-native @storybook/react

3. Configure Storybook

Add a folder in the root directory called .storybook . Now add main.js to the newly created storybook folder. This acts as the main configuration file for Storybook.

4. Create a component

For the purpose of this we’ll be creating a fairly simple LoadingButton component, this will make use of the React Native Button and ActivityIndicator components, accepting a loading prop which if true, will disable the button and display a loading indicator.

Create a src folder in the project root directory, then create a components folder.

Now create LoadingButton.tsx in the components folder and add the following code:

5. Create stories

Now that we’ve created our simple LoadingButton component, it’s time to create stories, again in the components folder, create LoadingButton.stories.tsx and add the following code:

This will allow us to see the both the default and the loading state of the button when we run Storybook.

6. Add Webpack config

Now we need to tell Webpack to use react-native-web instead of react-native when bundling the application, we do this by adding an alias.

Back in the .storybook folder, create webpack.config.js and add the following:

7. Add Storybook script and run

Our final step is to add a script to run Storybook. In the packages.json file, add the following script.

"scripts": {
... other scripts
"storybook": "start-storybook"
},

Now run the script with npm run storybook . This should run the script and open in a new tab and we can view our Loading Button component and the two states we defined.

The final rendered output — our Loading Button story

Caveats

As we are leveraging React Native for Web to render our React Native components, any limitations will also apply here, such as importing components not supported by React Native for Web.

You can download the source code at here.

--

--