Skip to content Skip to sidebar Skip to footer

React Router 4 -- Listen To Route Actions And Programmatically Continue/stop Routing

this is my scenario: I have a user form where user inputs details I want to create a confirmation message when user tries to leave current page i.e. 'Hey you have unsaved changes'

Solution 1:

There is a specific component in react-router just for that specific purpose: <Prompt>

Quoting from the readme:

Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a <Prompt>.

The <Prompt> has the when and the message props. The prompt is displayed when the user tries to navigate away and when is set to true. So, you can have a function set some bool variable to true/false according to your requirement and pass it as a prop to the <Prompt>.

For example:

//your component where you get user input

state = {
    name: "",
};

render() {
    return (
      <div><div><Promptwhen={!!this.state.name} /* triggersthedisplayofprompt */ 
                                  /*(checksifthis.state.nameisset)*/
            message={location => `You have unsaved changes. Are you sure you want to go to ${location.pathname}?`}
          />
          <div>Nice looking profile! What's your name?</div><inputvalue={this.state.name}onChange={e => this.setState({ name: e.target.value })} />
        </div></div>
    );
  }

Sample prompt

Codesandbox sample (not mine)

Find the tutorial here

Check the <Prompt> documentation here: docs

Post a Comment for "React Router 4 -- Listen To Route Actions And Programmatically Continue/stop Routing"