The useBlocker method is a hook that blocks navigation when a condition is met.
The useBlocker hook accepts a single optional argument, an option object:
An object with the controls to allow manual blocking and unblocking of navigation.
Two common use cases for the useBlocker hook are:
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
useBlocker({
blockerFn: () => window.confirm('Are you sure you want to leave?'),
condition: formIsDirty,
})
// ...
}
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
useBlocker({
blockerFn: () => window.confirm('Are you sure you want to leave?'),
condition: formIsDirty,
})
// ...
}
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
const { proceed, reset, status } = useBlocker({
condition: formIsDirty,
})
// ...
return (
<>
{/* ... */}
{status === 'blocked' && (
<div>
<p>Are you sure you want to leave?</p>
<button onClick={proceed}>Yes</button>
<button onClick={reset}>No</button>
</div>
)}
</>
}
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
const { proceed, reset, status } = useBlocker({
condition: formIsDirty,
})
// ...
return (
<>
{/* ... */}
{status === 'blocked' && (
<div>
<p>Are you sure you want to leave?</p>
<button onClick={proceed}>Yes</button>
<button onClick={reset}>No</button>
</div>
)}
</>
}
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.