Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router-dom refresh component when route changes

I used same component for different routes. When route changes, I want the component to be rendered.

<Switch>
    <Route exact path="/" component={HomePage} />
    <Route path="/hotels" component={HotelsPage} />
    <Route path="/apartments" component={HotelsPage} />
</Switch>

When I change the route path from /hotels to /apartments, the component HotelsPage doesn't refresh.

What is the cool approach for this?

like image 746
Smart Solutions Avatar asked Dec 13 '22 18:12

Smart Solutions


2 Answers

One of the ways you can get this sorted is by passing the props explicitly like :

<Route path="/hotels" component={props => <HotelsPage {...props} />} />

like image 184
Aaqib Avatar answered Dec 17 '22 22:12

Aaqib


Firstly you can aggregate the Route into one like

<Switch>
    <Route exact path="/" component={HomePage} />
    <Route path="/(hotels|apartments)" component={HotelsPage} />
</Switch>

and secondly, your HotelsPage component is rendered both on /hotels, /apartments, it is similar case like path params, whereby the component doesn't mount again on path change, but updates thereby calling componentWillReceiveProps lifecycle function,

What you can do is implement componentWillReceiveProps like

componentWillReceiveProps(nextProps) {
    if (nextProps.location.pathname !== this.props.location.pathname) {
      console.log("here");
      //take action here
    }
  }

DEMO

like image 34
Shubham Khatri Avatar answered Dec 17 '22 22:12

Shubham Khatri