score:1

try link and prompt with react-router-dom assuming you are using that:

import react from 'react'
import {
  browserrouter as router,
  route,
  link,
  prompt
} from 'react-router-dom'

const index = () => (
  <router>
    <div>
      <ul>
        <li><link to="/">form</link></li>
        <li><link to="/one">one</link></li>
        <li><link to="/two">two</link></li>
      </ul>
      <route path="/" exact component={form} />
      <route path="/one" render={() => <h3>one</h3>} />
      <route path="/two" render={() => <h3>two</h3>} />
    </div>
  </router>
)

class form extends react.component {
  state = {
    isblocking: false
  }

  render() {
    const { isblocking } = this.state

    return (
      <form
        style={{ margintop: '100px' }}
        onsubmit={event => {
          event.preventdefault()
          event.target.reset()
          this.setstate({
            isblocking: false
          })
        }}
      >
        <prompt
          when={isblocking}
          message={location => (
            `are you sure you want to go to ${location.pathname}`
          )}
        />

        <p>
          blocking? {isblocking ? 'yes, click a link or the back button' : 'nope'}
        </p>

        <p>
          <input
            size="50"
            placeholder="type something to block transitions"
            onchange={event => {
              this.setstate({
                isblocking: event.target.value.length > 0
              })
            }}
          />
        </p>

        <p>
          <button>submit to stop blocking</button>
        </p>

        <link to="/">click here to navigate</link>
      </form>
    )
  }
}

export default index

i just tried running this code, and it worked in an existing project.

see: https://reacttraining.com/react-router/web/example/preventing-transitions

this will hook to your router and detect navigation change and throw the message via <prompt /> if it detects navigating away.


Related Query

More Query from same tag