React Router is an external library for React that allows us to link specific URLs and display various components depending on which URL is displayed for server-side rendering.
This article will show you a few possible solution to You should not use <route> or withrouter() outside a <router> in React Router
error, so you can try applying and see whether they do the trick.
Sometimes, the error message would look like this :
Invariant Violation: You should not use <Route> or withRouter() outside a <Router>
Solution 1 : Define BrowserRouter in index.js to use route or withrouter() everywhere
Usually, React Router throws You should not use <route> or withrouter() outside a <router>
to warn that BrowserRouter
have not been defined and you are using Link
or NavLink
or Router
components.
Usually we want navigation over our entire app. In order to do that, we declare BrowserRouter
in index.js
file.
In index.js file, import BrowserRouter
from react-router-dom
package and wrap the App
component in it.
import React from 'react';
import ReactDOM from "react-dom";
import App from './App';
import {BrowserRouter} from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById("root")
);
Now you can easily use Link
, NavLink
, Route
etc. anywhere in your project without seeing You should not use <route> or withrouter() outside a <router>
ever again.
Solution 2 : Use Route to wrap App components
Alternatively, you can wrap App
inside Router
as it’s the correct way from React Router documentation. For example, with react-dom you need to wrap the app in Browser-Router. If this is a Udacity project, this is typically the index.js file.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter, Route} from 'react-router-dom'
const Root = () => {
return (
<BrowserRouter basename='/'>
<Route path={/
} component={App}></Route>
</BrowserRouter>
)
}
ReactDOM.render(<Root/>, document.getElementById('root'));
Thank you, you solved my problem 🙂