swoopy
swoopy

Reputation: 366

Error: Invariant failed: You should not use <Link> outside a <Router> (storybookjs)

It somehow works on normal react-scripts start. but when trying to view individual components via storybook it throws an error like a said on the title above.

here's my code.

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';


ReactDOM.render(<App />, document.getElementById('root'));

App.tsx

import React from 'react';
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
import { Register } from './pages/register/register'
import { Login } from './pages/login/login'
import { Home } from './pages/home/home'

const App: React.FC = () => {
  return (
    <div id="app-root">
      <BrowserRouter>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/register" exact component={Register} />     
          <Route path="/login" exact component={Login} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

login.tsx

export const Login = () => {
   return (
        <div className={styles.loginPage}>
            <div className={styles.body}>
                <div>
                    <Link to="/" className={styles.link}> 
                        <img src={arrowImage} className={styles.arrowImage} alt="arrowImage" />
                    </Link>
                </div>
            </div>
        </div>
   )
};

the other 2 components which is Home and Register practically has the same code with the login.tsx just different names. For some reason it works on the normal browser, but when I run storybook with the components it shows the error. I'm confused Im not sure what I've missed, as it is working on the normal browser without storybook.

storybook screenshot: https://user-images.githubusercontent.com/24859633/69216293-d38e0c80-0ba6-11ea-8434-201041f30af7.png

Upvotes: 1

Views: 3379

Answers (1)

wdc92
wdc92

Reputation: 111

Looks like a suggestion here from 'afholderman': https://github.com/storybookjs/storybook/issues/8892#issuecomment-580842862

import {MemoryRouter} from 'react-router-dom';
...
<MemoryRouter>
    <Link to="/" className={styles.link}> 
        <img src={arrowImage} className={styles.arrowImage} alt="arrowImage" />
    </Link>
</MemoryRouter>
....

Upvotes: 5

Related Questions