Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for Prompt in React Router V6

What is the alternative for Prompt in React Router V6, has it been deprecated, and also hooks like usePrompt, useBlocker are also not available.

<Prompt message="Are you sure you want to leave?" />
like image 920
Praveen Rao Chavan.G Avatar asked Dec 04 '25 21:12

Praveen Rao Chavan.G


2 Answers

You can use this util (checked on react-router-dom v6.9):

import { unstable_useBlocker as useBlocker } from 'react-router-dom'

function Prompt({ when, message }) {
    useBlocker(() => {
        if (when) {
            return ! window.confirm(message)
        }
        return false
    }, [when])

  return <div key={when} />
}

export default Prompt

Usage:

<Prompt when={condition} message='Are you sure you want to leave?'/>

** Edit, Feb 2024: **

Use react-router-prompt, availabe with react-router-dom >= 6.19

like image 144
o.z Avatar answered Dec 07 '25 10:12

o.z


Since React Router v6.7.0, the unstable_usePrompt hook is available. It requires using a data router, e.g. by calling createBrowserRouter (which is recommended for all new React Router web projects).

The documentation provides the following example:

function ImportantForm() {
  let [value, setValue] = React.useState("");

  // Block navigating elsewhere when data has been entered into the input
  unstable_usePrompt({
    message: "Are you sure?",
    when: ({ currentLocation, nextLocation }) =>
      value !== "" &&
      currentLocation.pathname !== nextLocation.pathname,
  });

  return (
    <Form method="post">
      <label>
        Enter some important data:
        <input
          name="data"
          value={value}
          onChange={(e) => setValue(e.target.value)}
        />
      </label>
      <button type="submit">Save</button>
    </Form>
  );
}

However, useBlocker is recommended instead for providing consistency across browsers as it enables handling how the confirmation message is styled. (It also requires a data router.) As of React Router v6.19.0, it no longer has the unstable prefix whereas there are no plans to remove the unstable prefix from unstable_usePrompt due to its non-deterministic behavior in different browsers.

like image 26
Unmitigated Avatar answered Dec 07 '25 11:12

Unmitigated