Here’s what worked for me:
- Create a
preview.jsfile in your.storybookfolder. - Add the following global decorator in your
preview.jsfile.
import React from "react";
import { addDecorator } from "@storybook/react";
import { MemoryRouter } from "react-router";
addDecorator(story => <MemoryRouter initialEntries={["https://stackoverflow.com/"]}>{story()}</MemoryRouter>);
Notes
- Storybook version used:
"@storybook/react": "^5.3.13" - Based on this solution here
- More about global decorators here
Edit: Update for Storybook V7 (Dec 2022)
-
Rename
preview.jstopreview.tsx(I guess it would work the same with jsx but my project is made in TypeScript) -
addDecoratorfunction is not available for v7 anymore so you need to add it like this.
import React from "react";
import { MemoryRouter } from "react-router";
export const decorators = [
(Story) => (
<MemoryRouter initialEntries={["https://stackoverflow.com/"]}>
<Story />
</MemoryRouter>
),
];