Installing Storybook is simple, and similar to what we did before; the react-native-storybook-loader package will let us place our *.story.js files wherever we want, and find them anyway. The second command will take a while, installing many packages; be warned! Also, a storybook directory will be created, at the root of your directory. Install Storybook with the following command:
npm install @storybook/cli react-native-storybook-loader --save-dev
npx storybook init
Running Storybook within an RN app created with CRNA requires an extra step: providing an appropriate App.js file. The simplest way to achieve this is with a one-liner file:
export default from './storybook';
However, this is a problem—how will you run your app? You could, of course, have two different App.storybook.js and App.standard.js files, and copy one or another to App.js, but that would quickly become boring if done manually. Of course, you could make do with some npm scripts. The following would work for Linux or macOS machines by using the cp command to copy files, but would require small changes for Windows devices:
"scripts": {
"start": "cp App.standard.js App.js && react-native-scripts start",
.
.
.
"storybook": "cp App.storybook.js App.js && rnstl && storybook start -p 7007"
},
We'll also need to add some configuration for the loader in package.json. The following makes the loader look for *.story.js files in the ./src directory, and generates a storyLoader.js file with the found stories:
"config": {
"react-native-storybook-loader": {
"searchDir": [
"./src"
],
"pattern": "**/*.story.js",
"outputFile": "./storybook/storyLoader.js"
}
},
Finally, we'll have to modify storybook/index.js, as follows:
import { getStorybookUI, configure } from "@storybook/react-native";
import { loadStories } from "./storyLoader";
configure(loadStories, module);
const StorybookUI = getStorybookUI({ port: 7007, onDeviceUI: true });
export default StorybookUI;
We are now set; let's write some stories!