Tell me how to access pathname
?
Parameter this.props
is empty and this.props.location
is undefined.
How to automatically get this parameter without having to set it yourself?
Most of the solutions found require me to set this parameter myself (manually), which is not very convenient and complicates the code.
ReactDOM.render(
<BrowserRouter>
<React.StrictMode>
<App />
</React.StrictMode>
</BrowserRouter>
document.getElementById('root')
);
function App() {
return (
<Container>
<Row><GeneralMenu /></Row>
<Row>
<Switch>
<Route exact path="/block1">
<PageStrategy />
</Route>
<Route exact path="/block2">
<PageStrategy />
</Route>
</Switch>
</Row>
</Container>
);
}
class GeneralMenu extends Component {
render() {
// {location} = this.props.location.pathname;
return (
<Navbar>
<Nav activeKey = {this.props.location.pathname}>
<Nav.Link href = "/block1">Block1</Nav.Link>
<Nav.Link href = "/block2">Block2</Nav.Link>
</Nav>
</Navbar>
);
}
}
You should use the withRouter()
HOC in your GeneralMenu
in this way:
export default withRouter(GeneralMenu);
and then use the exported element.
You can also do something like this, without export the element:
const WithRouterGeneralMenu = withRouter(GeneralMenu);