0

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>
        );      
    }
}
Zhihar
  • 1,306
  • 1
  • 22
  • 45
  • 1
    can it help? https://stackoverflow.com/questions/42253277/react-router-v4-how-to-get-current-route – Nikita Madeev Jun 05 '20 at 12:25
  • Does this answer your question? [React Pass history to a component defined in the Router](https://stackoverflow.com/questions/59453964/react-pass-history-to-a-component-defined-in-the-router) – wentjun Jun 05 '20 at 12:29
  • @Nikita Madeev, helped `withRouter` – Zhihar Jun 05 '20 at 13:32

2 Answers2

2

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);
Emanuele Scarabattoli
  • 4,103
  • 1
  • 12
  • 21
0
<Nav activeKey = {window.location.pathname}>

this option works!

And

<Nav.Link as = {Link} to = "/block1">

instead

<Nav.Link href = "/block1">

for site speed

Zhihar
  • 1,306
  • 1
  • 22
  • 45