0

I am using the "antd" framework for a react app and have one slight issues with menus, more precisely with highlighting the currently selected menu item.

I found the following solution that works fine when a link is called, an url is entered directly to a specific page and when "back" is pressed:

render() {
    const href = window.location.href.split('/');
    const href2 = href[3];
 <Menu
        mode="horizontal"
        theme="dark"
        defaultSelectedKeys={['/' + href2]}
        selectedKeys={['/' + href2]}
      >
    <Menu.Item key="/">
      ...
    </Menu.Item>
    <Menu.Item key="/test">
       ...
    </Menu.Item>
 <Menu>

My problem happens when I set my route from a redux saga (with history.push), I can then see that the "navigation bar" component gets rendered/updated before the "history.push" action is called in the saga.

How can I get my "navigation bar" component to be re-rendered after every route change (however the route change is done). My "navigation bar" is currently a component, because I tried to use the different events, but none of them gets fired. It could also be a functional component (it has no state) it that helps.

I also tried suggestions from "https://stackoverflow.com/questions/41054657/react-routerantd-how-to-highlight-a-menu-item-when-press-back-forward-button" but could not get it to work with my use case

marcel f
  • 288
  • 2
  • 15

1 Answers1

1

If you're using react-router library you shouldn't use window.location object. In your example of code, you're using the class component. In this case the component in <Route> receives location prop. And you can use it when you want

class Comp extends React.Component {
  componentDidUpdate(prevProps) {
    // will be true
    const locationChanged =
      this.props.location !== prevProps.location;
  }
}

<Route component={Comp} />;
Oro
  • 2,250
  • 1
  • 6
  • 22
  • Thank you for that example. In my main app I have a "" component and then some " ..." for the individual routes. But the "navbar" component is not defined as a route (as it only contains the menu item/links). My goal is to have the "navbar" component re-rendered whenever a route is called (and however it is called) I don't think that I can apply the code above to my navbar component or do I missunderstand something ? – marcel f Oct 14 '20 at 18:13
  • 1
    I think I found a solution based on your answer above. I pass the "location.pathname" from my main "app.tsx" to the "navbar" component: That way my component gets re-rendered on every change – marcel f Oct 14 '20 at 19:23