React Corsair - v0.0.10
    Preparing search index...

    Function useHistoryBlocker

    • Registers a blocker that prevents history navigation.

      Parameters

      • Optionalblocker: boolean | HistoryBlocker

        A history navigation blocker or a boolean that indicates whether blocker is blocked or not.

        • If true (or the callback returns true) then the transaction is blocked and the hook returns null.
        • If false (or the callback returns false) then the transaction isn't blocked and the hook returns null.
        • If undefined (or the callback returns undefined) then the transaction is blocked and the hook returns the pending transaction.

      Returns null | HistoryTransaction

      A pending navigation transaction that must be cancelled or proceeded. Or null if there's no blocked navigation transaction.

      const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

      useHistoryBlocker(transaction => {
      return hasUnsavedChanges && !confirm('Discard unsaved changes?')
      });
      const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

      useHistoryBlocker(transaction => {
      if (!hasUnsavedChanges) {
      // No unsaved changes, proceed with navigation
      transaction.proceed();
      return;
      }

      if (!confirm('Discard unsaved changes?')) {
      // User decided to keep unsaved changes
      transaction.cancel();
      }
      });
      const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);

      const transaction = useHistoryBlocker(() => hasUnsavedChanges);
      // or
      const transaction = useHistoryBlocker(hasUnsavedChanges);
      // or
      const transaction = useHistoryBlocker();

      transaction !== null && (
      <dialog open={true}>
      <p>{'Discard unsaved changes?'}</p>

      <button onClick={transaction.proceed}>{'Discard'}</button>
      <button onClick={transaction.cancel}>{'Cancel'}</button>
      </dialog>
      )