React component and hook which listens to the beforeunload window event.
npm install pair-question-anhnkbeforeunload window event.
jsx
useBeforeunload(handler);
`
#### Parameters
- handler function to be called with BeforeUnloadEvent when beforeunload event is fired.
#### Example
`jsx
import { useBeforeunload } from 'react-beforeunload';
const Example = (props) => {
const [value, setValue] = useState('');
useBeforeunload((event) => {
if (value !== '') {
event.preventDefault();
}
});
return (
setValue(event.target.value)} value={value} />
);
};
`
$3
`jsx
`
#### Props
- onBeforeunload function to be called with BeforeUnloadEvent when beforeunload event is fired.
#### Example
`jsx
import { Beforeunload } from 'react-beforeunload';
class Example extends React.Component {
state = { value: '' };
render() {
return (
<>
{this.state.value !== '' && (
event.preventDefault()} />
)}
onChange={(event) => this.setState({ value: event.target.value })}
value={this.state.value}
/>
>
);
}
}
`
:information_source: The Beforeunload component will render any children passed as-is, so it can be used as a wrapper component:
`jsx
`
Custom message support
To display a custom message in the triggered dialog box, return a string in the passed event handler function.
With useBeforeunload hook:
`jsx
useBeforeunload(() => 'You’ll lose your data!');
`
With Beforeunload component:
`jsx
'You’ll lose your data!'} />
``