Instructor: We're starting off with two routes already set up. One that we linked to here is just the home page, and the other is the profile. We have two components, one home and one profile that we'll focus on. If we go look in our browser, we can see that we have our home and profile set up.
Now, we want to be able to add a prompt if the user is editing any content. For example, if we are adding in some state, say our state equals name, we can then create an input, pass in our value, and then we'll add our onchange.
We'll type onchange equals. We'll have an arrow function that receives the event. We have this.setState of the name with e.target.value. Let's format this. Now, when we take a look in our browser, we could see that we now have an input that we can type our name into.
To prompt the user before navigation, we're going to import the prompt component from React Router DOM. We'll then set it up, and it does not take any children. We just wherever we render it, we must pass in the when.
The when will be true or false. True to prompt or false to allow navigation. We're going to add a double bang and say this.state.name. This will be when we have a name that isn't empty, we'll pass in true to when, and then we'll be prompted. The prompt will be whatever message that we set.
We can say message equals something, "Are you sure you want to leave?" If we test this, we can come in here. We can click on Home. Go back to our profile. As soon as we type something in and click on Home, we can see that we now prompted, "Are you sure you want to leave?" I'm going to cancel to stay here.
The other option for message is a function. This function with receive the location that you're attempting to navigate to. Then, we can either return a message that says, "Are you sure you want to go to a...turn this to a template literal, input location.pathname?"
If we go back to here, type in our name and attempt to navigate. We want to go to slash, which is our home wrap. We'll click OK. Finally, if this path name is a path that you want to allow navigation to, if location.pathname is equal to slash or whatever we want to return true to allow navigation, we can do that dynamically here.
If we return a string, it will prompt. If we return true by any sort of logic to the function of message, then it will always allow. If we go finally look at profile, type our name in and click on Home because we return true, it just allows the navigation and doesn't do any prompting regardless of what our when is.