Created
April 20, 2020 13:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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