navigate-away
TypeScript icon, indicating that this package has built-in type declarations

3.0.0 • Public • Published

build license npm minsize


⛵ Navigate away

Intercept and manipulate location changes

Intercept location changes before React paints them on screen.

Use this hook to manipulate the navigation flow, replace the next location or edit its state in a render friendly manner, before re-rendering the whole component tree.


Compatible with both react-router v6 and v5 API



Setup

pnpm add navigate-away
npm i navigate-away
yarn add navigate-away

Instructions are pretty simple, use the hook wherever you want!

Just be sure to always pass your app's router object to it (or history if working with react-router v5 API)

import { useNavigateAway } from 'navigate-away'
import { router } from 'src/store'

const Component = () => {
  useNavigateAway(({ nextLocation, action, navigate }) => {
    // do something with the location
    if (action === 'POP') {
      const updatedLocation = {
        ...nextLocation,
        state: {
          ...nextLocation.state,
          someFlag: true
        }
      }

      // then navigate
      navigate(updatedLocation)
    }
  }, router) // use the `history` object if working with `react-router` v5 API

  // ...
}

There is also a component version of the hook.

It comes handy when dealing with libraries such as Formik and you need to pass Formik props to the hook:

import { NavigateAway } from 'navigate-away'
import { router } from 'src/store'

const Component = () => {
  // ...

  return (
    <Formik>
      {(formikProps) => (
        <NavigateAway
          router={router}
          callback={({ nextLocation, action, navigate }) => {
            // use Formik props in the callback
          }}
        />
      )}
    </Formik>
  )
}

That's all, enjoy!





Used in production by Utilmond


react react-router

Package Sidebar

Install

npm i navigate-away

Weekly Downloads

0

Version

3.0.0

License

MIT

Unpacked Size

9.85 kB

Total Files

6

Last publish

Collaborators

  • fum4