Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storybook w/ react-router - You should not use <Link> outside <Router>

Posting the solution to a problem I had a hard time finding albeit Sensei Googling skills

Although my app with react-router worked without any problem Storybook threw the error "Invariant failed: You should not use outside ".

Error: Invariant failed: You should not use <Link> outside a <Router>
    at invariant (tiny-invariant.esm.js:11)
    at react-router-dom.js:181
    at updateContextConsumer (react-dom.development.js:19747)
    at beginWork$1 (react-dom.development.js:20079)
    at HTMLUnknownElement.callCallback (react-dom.development.js:358)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:410)
    at invokeGuardedCallback (react-dom.development.js:463)
    at beginWork$$1 (react-dom.development.js:25730)
    at performUnitOfWork (react-dom.development.js:24631)
    at workLoopSync (react-dom.development.js:24613)

Strange, as the app worked (and therefor no was used outside ).

like image 972
Natan Williams Avatar asked Nov 18 '19 07:11

Natan Williams


3 Answers

Here's what worked for me:

  1. Create a preview.js file in your .storybook folder.
  2. Add the following global decorator in your preview.js file.
    import React from "react";
    import { addDecorator } from "@storybook/react";
    import { MemoryRouter } from "react-router";
    
    addDecorator(story => <MemoryRouter initialEntries={['/']}>{story()}</MemoryRouter>);

Notes

  • Storybook version used: "@storybook/react": "^5.3.13"
  • Based on this solution here
  • More about global decorators here
like image 132
Fabian Merchan Avatar answered Oct 19 '22 20:10

Fabian Merchan


This is what worked for me. Add in the Memory Router inside the decorators property.

import React from 'react';
import {MemoryRouter} from 'react-router-dom';
import //your component// from //component location//

export default {
title : //How you want your component to show in storybook eg: 'Components/Button'
component : //Specify the name of component that you imported eg: 'Button'
decorators : [(Story) => (<MemoryRouter><Story/></MemoryRouter>)] //Wrapping the story inside the router
};
like image 32
Arjyo Bala Avatar answered Oct 19 '22 21:10

Arjyo Bala


For version 6.1 of Storybook works storybook-router in the new code notation. Here is an example for a single component:

import React from 'react';
import StoryRouter from 'storybook-react-router';
import //your component// from //component location//

export default {
  title: '//your component//',
  component: //your component//,
  decorators: [StoryRouter()],
};

export const Name = () => <//your component// />;
like image 6
Web-ski Avatar answered Oct 19 '22 19:10

Web-ski