Using React Router 4: Lesson 9 of 12

Blocking Transitions

Up Next

One Route, Multiple Places

Autoplaying in 7 seconds!

Cancel

Blocking Transitions

Let's explore how to block transitions. We are going to make it so that if we change any user information when adding or editing a user, the application will block any transitions away until we confirm that we want to transition away. For example, imagine we change some info and then want to cancel. It's just a way to make sure a user doesn't accidentally lose their work.

We get this functionality by using the Prompt component that ships with react-router-dom. Let's first add the prompt to the UserForm component. Place this at the top of the Form component returned from the render method.

<Prompt message="Are you sure you wanna do that?" />

We have created a Prompt and given it a prop of message. This will be the message the user sees when the prompt shows.

Also make sure to import the Prompt component into this file.

import { Prompt } from 'react-router-dom';

Now if you go to an edit page and then press the cancel button, the prompt will show up! However, we only want it to show up if we change some information in the form. Luckily, we can pass the Prompt component a when prop. When this is true, it will then show the prompt when a transition is attempted. If it's false, it won't show it. This means we need a variable in state that tracks whether information has been updated. This is easy since we have a single method that runs whenever an input is updated.

Inside UserForm, update the creation of state in the constructor method.

this.state = { user, formChanged: false };

Next, inside handleChange, make sure state is updated so we know the form data has been changed.

handleChange(e, { name, value }) {
  const { user } = this.state;

  this.setState({
    user: { ...user, [name]: value },
    formChanged: true,
  });
}

Pull this formChanged piece of state out of state in the render method.

const { user: { name, email, phone, address, city, zip }, formChanged } = this.state;

Lastly, pass the value of formChanged as the when prop to the Prompt component we just created.

<Prompt when={formChanged} message="Are you sure you wanna do that?" />

Now, try changing some data in an edit form and see what happens. The prompt shows up like before. Now reload that page and just click on the "Cancel" button. It doesn't show the prompt! Awesome! That wasn't too bad.

In the next video, we will discuss how we can show multiple routes that both match in separate areas.

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?