V
V
Vladimir Golub2019-08-16 17:08:14
React
Vladimir Golub, 2019-08-16 17:08:14

How to close the menu when changing the address?

When changing the page, I want to close the menu.

componentDidUpdate(prevProps, prevState, snapshot) {
        if (this.state.menuMobile) {
            if (this.props.location.pathname !== this.props.history.location.pathname) {
                this.setState({
                    menuMobile: false
                })
            }
        }
    }

Why are this.props.location.pathname and this.props.history.location.pathname suddenly equal?
I make the transition to the page like this: The problem occurs precisely when you go to the main page, there are no problems on the rest.
<NavLink to="/" >

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-08-19
@RazerVG

Why are this.props.location.pathname and this.props.history.location.pathname suddenly equal?

Because location and history.location are the same object. Your condition will never be fulfilled.
You can fix it like this:
componentDidUpdate(prevProps) {
  if (
    prevProps.location.pathname !== this.props.location.pathname &&
    this.state.menuMobile
   ) {
    this.setState({ menuMobile: false });
  }
}

K
Kirill Udaltsov, 2019-08-16
@uashkki

Try like this:<NavLink exact to="/" >

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question