npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-use-navigate

v0.1.1

Published

Easy and expressive conditional navigation in React

Downloads

563

Readme

react-use-navigate

Easy, flexible, and expressive hook based navigation in React.

Features

  • Tiny. Simple. Expressive. 1.5kb gzipped.
  • TypeScript ready
  • React framework agnostic (Next.js, Gatsby, React Router, Reach Router, etc.)
  • Glob pattern matching support

Motivation

Often times we want to navigate pages conditionally. This can easily turn into a bunch of if else statements and regex matching. Here's some code that redirects a logged out user to /login if they on a page under the /app directory. If they are logged in but not in the app, they are redirected to the app dashboard.

useEffect(() => {
  const inApp = new RegEx(`/${location.hostname}\/app\/([0-9A-Za-z]+\/?)+/`)
  if(!isLoggedIn && inApp) {
    return goTo('/login')
  }
  if(isLoggedIn && !inApp) {
    return goTo('/app/dashboard')
  }
}, [isLoggedIn])

Not complicated to follow (aside from the regex), but for something so easy to express in words, it sure doesn't look it. Using the useNavigate() hook, here's what the same code would look like:

const { replace } = useNavigate()

useEffect(() => {
  replace({
    goTo: '/login',
    when: !isLoggedIn,
    onPaths: ['/app/**'], // glob pattern matching goodness
    otherwiseGoTo: '/app/dashboard', // this will only trigger if when === false AND path requirements fail
  })
}, [isLoggedIn])

This can almost be read as sentence, roughly translating to, "go to /login when user is not logged in while on any app directory. Otherwise, go to the app dashboard."

But what if we want to navigate a user when they aren't on a page in a particular directory? For example, maybe we have multiple apps like /analytics and /editor. Perhaps we want to just be general and say "send the user to login if they aren't on a marketing page". No problem, here's the same code as above with a slight modification:

const { replace } = useNavigate()

useEffect(() => {
  replace({
    goTo: '/login',
    when: !isLoggedIn,
    notOnPaths: ['/marketing/**'], // navigates when a user isn't on a matching page
  })
}, [isLoggedIn])

Installation

yarn add react-use-navigate
npm install react-use-navigate

This package has a peer dependency on React and React DOM > 16.8.0 (basically you need react hooks).

Setup

This hook doesn't care how navigation works, it just asks that you provide the logic for the basic navigation methods push, replace, and back.

This can be done with a config object in the NavigateProvider. Below are a few examples in different frameworks.

Using React Router

import { NavigateProvider } from 'react-use-navigate'

const App = () => {
  const history = useHistory()
  
  const config = {
    push: history.push,
    back: history.back,
    replace: history.replace
  }

  return (
    <NavigateProvider {...config}>
      <RootComponent/>
    </NavigateProvider>
  )
}

Using Next.js

import { NavigateProvider } from 'react-use-navigate'

function MyApp({ Component, pageProps }) {
  const router = useRouter()

  const config = {
    push: router.push,
    back: router.back,
    replace: router.replace
  }

  return (
    <NavigateProvider {...config}>
      <Component {...pageProps} />
    </NavigateProvider>
  )
}

API Reference

useNavigate()

const { push, back, replace } = useNavigate()

Each navigation method uses the same paramters:

type UseNavigateProps = {
  when?: boolean
  goTo?: string
  onPaths?: string[] // array of globs
  notOnPaths?: string[]
  otherwiseGoTo?: string
}

| Property | Description | type | required | | |---------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|----------|---| | when | base condition that must be met to navigate | boolean | false | | | goTo | the link to go to | string | true | | | onPaths | navigation will occur only if a user is on one of the specified paths. Will take precedence over notOnPaths field | string[] | false | | | notOnPaths | navigation will occur only if a user is not on any of the specified paths. | string[] | false | | | otherwiseGoTo | The link to go to if when === false and onPaths or notOnPaths is also false. If the latter two fields aren't specified, it will navigate if when === false. | string | false | |