Search code examples
storybook

Specify default page for Storybook


I have storybook in my React app, and for some reason when i run yarn storybook it's always open the same story (it's automatically select selectedKind and selectedStory) . How can i manually select default story?


Solution

  • The Kind and Story are selected based on the URL query parameters (i.e. http://localhost:9001/?selectedKind=Component&selectedStory=default will select the Component kind and default story). If you don't have any URL parameters, then storybook will choose the first story in the list (which is the first story loaded via however you have storybook configured).

    If you just want to choose the first story in the list, then load you story files in a specific order in your loadStories function in .storybook/config.js file.


    If, however, you want to always force the same story to be selected, then follow the instructions below.

    The best way to do this would be to use the Storybook's addonAPI. Here is an example that worked for me (with a safeguard so you don't get stuck on the same story forever):

    // .storybook/addons.js
    import addonAPI from '@storybook/addons';
    
    let firstLoad = true;
    addonAPI.register('my-organisation/my-addon', (storybookAPI) => {
      storybookAPI.onStory((kind, story) => {
        // when you enter a story, if you are just loading storybook up, default to a specific kind/story. 
        if (firstLoad) {
          firstLoad = false; // make sure to set this flag to false, otherwise you will never be able to look at another story.
          storybookAPI.selectStory('FirstKind', 'default story');
        }
      });
    });
    
    

    With that snippet, no matter what story you end up on based on the URL, you can select the first story to land on.

    You can read more about the storybook addonAPI here: https://storybook.js.org/addons/api/ I would probably allow an additional query parameter in the URL to force the kind+story from the URL to be chosen.

    Note: there may be an existing addon that provides this functionality, but a quick search yielded no viable results.