Skip to content

Instantly share code, notes, and snippets.

@imjakechapman
Last active April 20, 2020 12:50
Show Gist options
  • Save imjakechapman/89fb00cd8c14fa667f1b326b340e5fb8 to your computer and use it in GitHub Desktop.
Save imjakechapman/89fb00cd8c14fa667f1b326b340e5fb8 to your computer and use it in GitHub Desktop.
Utility function to temporarily match parts of pathname to add active classes onto top level NavLink component in nested routers
function nestedMatch(test: string, type: string = "", path: string = location.pathname): boolean {
switch(type) {
case 'startsWith':
return path.match(new RegExp(`^\/${test}`))?.length ? true : false
case 'endsWith':
return path.match(new RegExp(`/${test}$`))?.length ? true : false
default:
return path.match(new RegExp(`${test}`))?.length ? true : false
}
}
// location.pathname = "/account/9gua9109gj1kkljas/edit"
assert(nestedMatch("account"), true) // pass
assert(nestedMatch("account", "startsWith"), true) // pass
assert(nestedMatch("account", "endsWith"), false) // pass
assert(nestedMatch("edit"), true) // pass
assert(nestedMatch("edit", "startsWith"), false) // pass
assert(nestedMatch("edit", "endsWith"), true) // pass
assert(nestedMatch("9gua9109gj1kkljas", "startsWith"), false) // pass
assert(nestedMatch("9gua9109gj1kkljas", "endsWith"), false) // pass
assert(nestedMatch("9gua9109gj1kkljas"), true) // pass
// Example
<Router>
<nav>
<NavLink
to="/account"
activeClassName="active"
className={classnames(
{ "nestedActive": nestedMatch("account", "startsWith")}
)}
>
Account
</NavLink>
</nav>
<Routes>
<Route
path="/accounts/*"
element={<Accounts />}
>
<Route path=":id" element={<AccountEdit />} />
</Route>
</Routes>
</Router>
const Account = () => {
const { id } = useParams();
return (
<NavLink
to=`${id}/edit"
activeClassName="active"
className={
classnames({ "nestedActive": nestedMatch("edit", "startsWith") })
}
>
Edit Account
</NavLink>
<p>My Account</p>
)
}
const AccountEdit = () => {
return (
<p>Edit your account</p>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment