Search code examples
javascriptreactjsreact-routerstorybook

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 <Link> outside <Router>".

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 <Link> was used outside <Router>).


Solution

  • The problem was Storybook rendering the individual stories. In this case the component using <Link> was in fact rendered outside a <Router>.

    The solution was to wrap the individual stories with the <Router> using addDecorator;

    //config.js
    //...
    addDecorator(story => <Router>{story()}</Router>);