Using React Router 4: Lesson 6 of 12

Using history

Up Next

Child Routes

Autoplaying in 7 seconds!

Cancel

Using History

Now that we have the user's info showing, we need to add the functionality to redirect to the /users route after deleting the user through the API. Since we need to redirect after the API returns a response, we can't just use Link to go back. We need to manually do it. React Router makes this easy by passing a history object into each route as a prop. This history object lets us manually control history of the browser. Since React Router is made to change what we see based off of the current URL, the history object can gives us fine-grained control of when and where certain pieces of the application are shown.

To cause the change we want to happen, we need to push a new route onto the browser's history. React Router will pick this up and update the view accordingly. In src/fe/components/UserInfo.js, update the handleDelete method to look like this.

handleDelete() {
  const { match: { params }, history } = this.props;

  axios.delete(`/api/users/${params.userId}`)
    .then(() => {
      history.push('/users');
    });
}

Now try deleting a user. Notice how after the user is deleted, the modal is closed, and we are back at the users table. That was simple.

Now that we have deleting working fine, let's explore child routes by reorganizing some of the routes we currently have in the next video.

Alex Sears

2 posts

Developing is not only my job but also my passion. I love to teach myself new things as much as I love teaching others. The more people we get involved in this little thing we call "web development," the better we can make it. I mean, we always need more cat videos, right?