reactjsstorybookreact-portal

How to preview a React Portal component using storybook


I have this code:

index.html

...
<body>
  <div id="example-root"></div>
</body>
...

Component.tsx

...
const exampleRoot = document.getElementById("example-root")

function Component() {
  return ReactDOM.createPortal(<div>...</div>, exampleRoot)
}

Stories.tsx

...
const ExampleStory = () => (
  <>
    <div id="example-root"></div>
    <Component />
  </>  
)

I need to render <Component/> on storybook, but the problem is that <Component/> needs to find the #example-root element to be rendered, but when I run the storybook it's unable to find this root element and it can't be rendered, but when I run the same code at normal page it works fine, except in storybook, so the problem is on storybook.

I think it's happening because the <Component /> is mounted before the storybook, so the the component can't find the #example-root element. A funny thing is that after everything has been rendered(component & storybook) if I do any change at <Component /> code and save it, then it works! The <Component /> find the root and is rendered.

So, how do I solve this?


Solution

  • I found the answer for this

    If you need to render a component that is a React Portal, go to .storybook folder in your workspace, and then create a new file called preview-body.html, inside this file you just need to create the portal root tag, for example:

    // .storybook > preview-body.html
    
    <div id="example-root"></div>
    

    Now your React Portal component is ready to be rendered in your story.