react-beforeunload
DefinitelyTyped icon, indicating that this package has TypeScript declarations provided by the separate @types/react-beforeunload package

2.6.0 • Public • Published

react-beforeunload

Listen to the beforeunload window event in React.

Usage

useBeforeunload Hook (recommended)

useBeforeunload(handler);

Parameters

  • handler optional function to be called with BeforeUnloadEvent when beforeunload event is fired.

Example

import { useBeforeunload } from 'react-beforeunload';

const Example = (props) => {
  const [value, setValue] = useState('');

  useBeforeunload(value !== '' ? (event) => event.preventDefault() : null);

  return (
    <input onChange={(event) => setValue(event.target.value)} value={value} />
  );
};

Beforeunload Component

<Beforeunload onBeforeunload={handler} />

Props

  • onBeforeunload function to be called with BeforeUnloadEvent when beforeunload event is fired.

Example

import { Beforeunload } from 'react-beforeunload';

class Example extends React.Component {
  state = { value: '' };

  render() {
    return (
      <>
        {this.state.value !== '' && (
          <Beforeunload onBeforeunload={(event) => event.preventDefault()} />
        )}
        <input
          onChange={(event) => this.setState({ value: event.target.value })}
          value={this.state.value}
        />
      </>
    );
  }
}

ℹ️ The Beforeunload component will render any children passed as-is, so it can be used as a wrapper component:

<Beforeunload onBeforeunload={}>
  <MyApp />
</Beforeunload>

Custom message support

⚠️ Some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. However, this is deprecated and no longer supported in most browsers.

Source

To display a custom message in the triggered dialog box, return a string in the passed event handler function.

With useBeforeunload hook:

useBeforeunload(() => 'You’ll lose your data!');

With Beforeunload component:

<Beforeunload onBeforeunload={() => 'You’ll lose your data!'} />

Requirements

Requires a minimum of React version 16.8.0. If you're on an older version of React, then checkout v1.

Dependencies (0)

    Dev Dependencies (16)

    Package Sidebar

    Install

    npm i react-beforeunload

    Weekly Downloads

    80,283

    Version

    2.6.0

    License

    MIT

    Unpacked Size

    11.8 kB

    Total Files

    7

    Last publish

    Collaborators

    • jacobbuck