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:
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'));
Main
componentexport 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.
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 .
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") );
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.
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.
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(); }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With