vesperae vesperae - 9 months ago 114
Javascript Question

React Router, lifecycle when browser's back button is clicked

I want to detect when the user has hit the back button. Essentially, when a user goes from the /projects to /projects/foo the nav style changes.

<Route path="/projects" component={(props, state, params) =>
<Projects {...props} />

This works fine when detecting an onClick event from /projects to a specific project, but when the user hits the back button
is not called... I'm trying to use
to determine the specific path, but as I need to set state I cannot do this inside

Is there a "react" way of going about this? Thx

Answer Source

As you noted, componentDidMount will only be called once when the component is mounted. Instead, use the lifecycle hook componentWillReceiveProps. Here is the documentation.

You can use this to conditionally setState if you're at the desired/correct path. This will update the state which will then re-render the component.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download