Skip to content

Instantly share code, notes, and snippets.

@salmanx
Created October 24, 2025 12:15
Show Gist options
  • Select an option

  • Save salmanx/98f474472efd2b96561c214baf2aa4a2 to your computer and use it in GitHub Desktop.

Select an option

Save salmanx/98f474472efd2b96561c214baf2aa4a2 to your computer and use it in GitHub Desktop.
import { useLocation } from "react-router-dom";
export function useIsAllowed(allowed: string[]) {
const { pathname } = useLocation();
// Normalize the current path (remove trailing slashes, keep root as '/')
const normalizedPath =
pathname.replace(/\/+$/, '') === '' ? '/' : pathname.replace(/\/+$/, '');
return allowed.some((pattern) => {
let normalizedPattern = pattern.replace(/\/+$/, '');
// Ensure pattern starts with '/'
if (!normalizedPattern.startsWith('/')) {
normalizedPattern = '/' + normalizedPattern;
}
// Handle wildcard (like /prospect/*)
if (normalizedPattern.endsWith('/*')) {
const base = normalizedPattern.slice(0, -2); // remove /*
// Match base route or any nested path
return (
normalizedPath === base ||
normalizedPath.startsWith(base + '/')
);
}
// Exact match
return normalizedPath === normalizedPattern;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment