1.1.1 • Published 2 years ago
react-hook-use-prevent-leave v1.1.1
react hook: usePreventLeave
npm i react-hook-use-prevent-leave
- A react custom hook to prompt confirm dialog when user tries to close the tab or refresh the page
- Supports TypeScript
- DEMO: https://tzynwang.github.io/react-hook-use-prevent-leave/
- NOTE: This hook will NOT block the navigation leave; to prompt a confirmation for this, use
Prompt
fromreact-router-dom
(also includes in the example codes)
Example
import React, { useState } from 'react';
import { Prompt } from 'react-router-dom';
import usePreventLeave from 'react-hook-use-prevent-leave';
function PageShouldBeBlocked(): React.ReactElement {
/* State */
const [blockPage, setBlockPage] = useState<boolean>(true);
/* Function */
function togglePageBlock(): void {
setBlockPage((prev) => !prev);
}
/* Hook */
usePreventLeave(blockPage);
// Or just call usePreventLeave() without passing any params, this mean the page will always be blocked.
/* Main */
return (
<React.Fragment>
<Prompt when={blockPage} message={'Confirm to leave this page?'} />
<div>This page is {!blockPage && 'NOT'} block now.</div>
<button onClick={togglePageBlock}>Click to toggle block or not.</button>
</React.Fragment>
);
}
export default PageShouldBeBlocked;
Author
1.1.1
2 years ago
1.1.0
2 years ago
1.0.0
2 years ago
0.0.1-beta.4
2 years ago
0.0.1-beta.3
2 years ago
0.0.1-beta.2
2 years ago
0.0.1-beta.1
2 years ago