DEV Community

Goulart
Goulart

Posted on • Edited on

Using Storybook with React Native

Hi folks πŸ‘‹

Im this guide we will setup a new react native application using storybook.


Context Overview

In the last few days, I felt the need to create a ui library for react native, shared in multiple projects to maintain a product design standard.

Looking for solutions and the best way to do that Ive found storybook as great solution for documentation.

A life savior for new members in team and a nice gift for ui/ux team. πŸ₯‚βœ¨


Informations

This guide assume you are using a React Native CLI project.
Not guarantee that guide work in Expo projects


Step 1: Install Storybook ✨

Open your project folder and run:

npx -p @storybook/cli sb init --type react_native

When it prompts you whether to install @storybook/react-native-server, hit Y to install.

After a little bit you will see something like this:
Post install Storybook/cli

Storybook Server runs outside of your app screen. You can develop UI, switching between components and manipulating knobs in isolation without worrying about app specific dependencies and requirements.

Step 2: Change Storybook config

After step 1, open your code editor and we will do the final steps in rendering storybook out on the screen.

Open storybook/index.js and change to:

import {getStorybookUI, configure, addDecorator} from '@storybook/react-native';
import {withKnobs} from '@storybook/addon-knobs';

import './rn-addons';

// enables knobs for all stories
addDecorator(withKnobs);

// import stories
configure(() => {
  require('./stories');
}, module);

// Refer to https://github.com/storybookjs/storybook/tree/master/app/react-native#start-command-parameters
// To find allowed options for getStorybookUI
const StorybookUIRoot = getStorybookUI({});

export default StorybookUIRoot;
Enter fullscreen mode Exit fullscreen mode

After that go to your index.js and change to below code.

To switch between viewing the app with StoryBook or without just change the useStorybook variable to some boolean.

import React from 'react';
import {AppRegistry} from 'react-native';
import App from './App';
import StoryBook from './storybook';
import {name as appName} from './app.json';

const useStorybook = true;

const AppRegistred = () => (useStorybook ? <StoryBook /> : <App />);

AppRegistry.registerComponent(appName, () => AppRegistred);
Enter fullscreen mode Exit fullscreen mode

With useStorybook True With useStorybook False
Alt Text Alt Text

You can also run Storybook in web browser, just running:

yarn storybook

Storybook react native in web

Success!

Hope this helps :)

Top comments (0)