matchPath

Description

matchPath is a function that tells if the path of the first argument matches the path of the second argument by returning an object or null.

Basic Usage

Assume that you are on /about page.

GlobalNav.jsx
import {matchPath} from 'react-queue-router'

const {pathname} = window.location
console.log(pathname) // /about

const matched01 = matchPath(pathname, '/about')
console.log(matched01)
// {
//   isExact: true,
//   params: {},
//   path: "/about",
//   url: "/about"
// }

const matched02 = matchPath(pathname, {path: '/about', exact: true}) // you can pass an object 
console.log(matched02)
// {
//   isExact: true,
//   params: {},
//   path: "/about",
//   url: "/about"
// }

const matched03 = matchPath(pathname, '/contact') // when unmatched, null will be returned 
console.log(matched03)
// null

Practical Example

matchPath is useful to implement a global navigation with the combination of currentPath or nextPath.

In the code below, is-current is added to li when nextPath matches.

GlobalNav.jsx
import React, {useContext} from 'react'
import {RouterContext, matchPath, Link} from 'react-queue-router'

const GlobalNav = () => {
  const {nextPath} = useContext(RouterContext)
  
  return (
    <ul>
      <li className={matchPath(nextPath, '/') ? 'is-current' : ''}>
        <Link to='/'>Top page</Link>
      </li>
      <li className={matchPath(nextPath, '/about') ? 'is-current' : ''}>
        <Link to='/about'>About page</Link>
      </li>
    </ul>
  )
 }
 
export default GlobalNav