whiterook6
whiterook6

Reputation: 3544

Updating react components when the query string changes

I need a component to rerender when another component changes the query/search string.

To change the url I'm using history.push():

private updateURL(date: Date) {
    const url = `/?date=${formatDate(date)}`; // /?date=2019-01-01
    history.replaceState(
        {},
        `Dashboard for ${formatDate(date)}`,
        url
    );
}

In my navigation bar, I want to update my links so they can share the querystring between URLs. This works if I use withRouter:

class Sidebar extends React.Component {
    public render(){
        return <Link to={`/anotherPage?${this.props.location.search}`}>Visit</Link>;
    }
}

export default withRouter(Sidebar);

If I use a Redirect object instead of history.push(), the sidebar updates as it should and that's fine. Does that mean it will unmount the whole view, render the redirect, then remount the whole view? That would be undesirable if that means unmounting and remounting complex svg maps, for example.

constructor(props){
  super(props);
  this.state = {
    redirect: null;
  }
}

private updateURL(date: Date){
  this.setState({
    redirect: `/?date=${formatDate(date)}`
  });
}

public render(){
  if (this.state.redirect){
    return <Redirect to={this.state.redirect} />;
  } else {
    // render dashboard, map, charts, etc.
  }
}

If I cannot or do not want to use <Redirect />, is there an alternative that would cause the sidebar to update when the query string changes due to history.push?

Upvotes: 2

Views: 1906

Answers (1)

GProst
GProst

Reputation: 10237

You can easily check it by placing console.log in componentDidMount for example, but given how React works I believe it will unmount/mount as you suspected. So a better solution would be to use history.replace() API that react-router also provides:

private updateURL(date: Date){
  this.props.history.replace(`/?date=${formatDate(date)}`);
}

Upvotes: 1

Related Questions