2

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?

1

1 Answer 1

1

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)}`);
}
Sign up to request clarification or add additional context in comments.

2 Comments

So I would have to wrap whichever component wants to update the URL bar with withRouter(...), right?
In order to get history object? Yes, or pass it down from parent components. Components which you pass to Route component (like <Route component={MyComponent} />) have history prop by default

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.