Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

You should not use <Link> outside a <Router>

I'm trying to set up react-router in an example application, and I'm getting the following error:

You should not use <Link> outside a <Router> 

My app is set up like so:

Parent component

const router = (   <div className="sans-serif">     <Router histpry={browserHistory}>       <Route path="/" component={Main}>         <IndexRoute component={PhotoGrid}></IndexRoute>         <Route path="/view/:postId" component={Single}></Route>       </Route>     </Router>   </div> );  render(<Main />, document.getElementById('root')); 

Child/Main component

export default () => (   <div>     <h1>       <Link to="/">Redux example</Link>     </h1>   </div> ) 

Any idea what I'm doing wrong here?

Here's a Sandbox link to demonstrate the problem.

like image 820
A7DC Avatar asked Feb 06 '18 10:02

A7DC


People also ask

Can we use link outside Router?

To fix the 'You should not use Link outside a Router' error with React Router, we should make sure Link is only used in components that are inside Router .

Should not Use route or Withrouter () outside a Router?

To fix the 'You should not use Route or withRouter() outside a Router' error with React Router v4, we should wrap our app with the BrowserRouter component. import { BrowserRouter } from "react-router-dom"; ReactDOM. render( <BrowserRouter> <App /> </BrowserRouter>, document. getElementById("root") );

Should we use HREF in react?

This href attribute contains the URL or path to the destination page. It may be a relative URL or an absolute URL. In React, relative URLs should always be handled by the link tag provided by the React Router, and pure anchor tags should only be used for absolute paths.

What is memory Router react?

Memory Router: Memory router keeps the URL changes in memory not in the user browsers. It keeps the history of the URL in memory (does not read or write to the address bar so the user can not use the browser's back button as well as the forward button. It doesn't change the URL in your browser.


1 Answers

For JEST users

if you use Jest for testing and this error happen just wrap your component with <BrowserRouter>

describe('Test suits for MyComponentWithLink', () => { it('should match with snapshot', () => { const tree = renderer   .create(     <BrowserRouter>       <MyComponentWithLink/>     </BrowserRouter>   )   .toJSON();  expect(tree).toMatchSnapshot();  }); }); 
like image 157
MBehtemam Avatar answered Sep 28 '22 08:09

MBehtemam