React Component stories can be dynamically loaded into React Storybook instead of doing it manually every time.
Here we have a running Storybook, and we have few stories. We define our stories inside the stories directory, inside this [indecipherable 0:07] directory.
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.
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.
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.
I want to look at all the subdirectories inside this directory, so I give it true. Let's make my editor bigger.
Now I'm going to create a regular expression to match my stories files. That should be .stories.js extension. That's it.
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.
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.
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.
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.
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.
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.
Now I can even remove my stories directory completely because I'm not loading stories from this directory any more.
Just like this, you can depend any pattern you like as require.context and load stories from wherever you want inside your project.