I use react-router-dom
for routing in my React
application. Part of my app extracted in another package. List of dependencies looks like this:
I had the same problem with my Create React App when running tests and I solved it by placing <Router></Router
inside App.js
instead of in Index.js
as I have always done.
Before:
Index.js
ReactDOM.render(
<React.StrictMode>
<GlobalStyle />
<Router>
<App />
</Router>
</React.StrictMode>,
document.getElementById('root')
);
App.js
return (
<div className="App">
<Header />
<Route path="/blabla" component={Whatever}
</div>
)
After:
Index.js:
ReactDOM.render(
<React.StrictMode>
<GlobalStyle />
<App />
</React.StrictMode>,
document.getElementById('root')
);
App.js:
return (
<div className="App">
<Router>
<Header />
<Route path="/blabla" component={Whatever}
</Router>
</div>
)
I have solved this issue by importing
import {BrowserRouter as Router, Route} from 'react-router-dom';
and wrapped all the Route
components under the Router
component
<Router>
<Route exact path='/' component={HomePage} />
</Router>
just change "react-router" on "react-router-dom"
import {Route} from "react-router";
to
import {Route} from "react-router-dom";
I fixed that problem just importing the "BrowserRouter" from 'react-router-dom' in index.js(on create-react-app) then you can use:
<BrowserRouter>
<App>
</BrowserRouter>
replacing where were:
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'));
Using the <Link>
tag in a component that doesn't have the imported could give this error, try importing the BrowserRouter
from 'react-router-dom'
import {BrowserRouter , Link} from 'react-router-dom';
then make sure to wrap your linked tags in the tag
You have a hanging comma at the end of the render call after document.getElementById('root')
.
render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root'),
);