Load React Storybook Stories Dynamically

Share this video with your friends

Social Share Links

Send Tweet

React Component stories can be dynamically loaded into React Storybook instead of doing it manually every time.

[00:00] Here we have a running Storybook, and we have few stories. We define our stories inside the stories directory, inside this [indecipherable] directory.

[00:08] It could be really nice if we can define stories right inside the components directory. For example, for the main section component, if we can write stories in a file called mainsection.stories.js, that would be interesting. That's what we're going to do right now.

[00:24] Now let's open our config.js file inside our .storybook directory. Now we're going to use a feature in webpack called require.context. They're trying to create a custom require function. Let's do that.

[00:41] I'm going to type constreq, and I'm typing require.context. I need to go base directory, where I am looking files at, it's ready to be a /c/component.

[00:56] I want to look at all the subdirectories inside this directory, so I give it true. Let's make my editor bigger.

[01:06] Now I'm going to create a regular expression to match my stories files. That should be .stories.js extension. That's it.

[01:19] Now I have a custom require function. It's time to use this new require function we just created. I can remove this line. Existing line we have reload stories, and then I will type in req.key.

[01:35] This will give us all the match files for this extension inside the components directory. I am iterating over that, and I'm loading those files, actually requiring those files.

[01:47] For that, I'm going to use this path and I'm going to require using this new require function we just created, and path, and I hit save.

[02:00] Then I can reload my storybook, and there won't be any stories. That's because we haven't created a file like this inside my components directory.

[02:11] Let's create our first stories.js file. Let's go inside our existing stories directory, and I'm going to rename this mainsection.js file as mainsection.stories.js. Then I'm going to copy this file and paste it inside the components directory.

[02:36] Now we have a file called mainsection.stories.js inside my components directory, and I can see there are some stories inside the mystorybooks loaded from this stories.js file. I can reload it and confirm it's working properly.

[02:52] Now I can even remove my stories directory completely because I'm not loading stories from this directory any more.

[03:01] Just like this, you can depend any pattern you like as require.context and load stories from wherever you want inside your project.