Skip to content

Instantly share code, notes, and snippets.

@imjakechapman
Created April 20, 2020 13:23
Show Gist options
  • Save imjakechapman/97a8c2250800acaea77b4b80b9144747 to your computer and use it in GitHub Desktop.
Save imjakechapman/97a8c2250800acaea77b4b80b9144747 to your computer and use it in GitHub Desktop.
React Router V6 Hook to help with nested routers and top level NavLink's maintain an active class
import { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";
export const useNestedMatch = (test, type = "") => {
const { pathname } = useLocation();
const [match, setMatch] = useState(false);
useEffect(() => {
let result;
switch (type) {
case "startsWith":
result = pathname.match(new RegExp(`^/${test}`))?.length ? true : false;
break;
case "endsWith":
result = pathname.match(new RegExp(`/${test}$`))?.length ? true : false;
break;
default:
result = pathname.match(new RegExp(`${test}`))?.length ? true : false;
break;
}
setMatch(result);
}, [test, type, pathname]);
return match;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment