I wrote this code:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router, Route } from "react-router-dom";
import AboutPage from './pages/aboutPage'
ReactDOM.render(
<React.StrictMode>
<Router>
<Route path='/' component={ App }/>
<Route path='/about' component={ AboutPage }/>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
Why doesn't it work? I'm getting this error:
How can I fix it? React v17.0.2, React-router v5.2.1, React-router-dom v6.0.1
CodePudding user response:
A Route
is only ever to be used as the child of Routes
element, never rendered directly. So just wrap your <Route>
in a <Routes>
<Router>
<Routes>
<Route path='/' component={ App }/>
<Route path='/about' component={ AboutPage }/>
</Routes>
</Router>
CodePudding user response:
Wrap your component (the one where you're using props.location
) with the withRouter
to inject the former:
import { withRouter } from 'react-router-dom';
class MyComponent extends React.Component {
...
}
export default withRouter(MyComponent);