Created
October 24, 2025 12:15
-
-
Save salmanx/98f474472efd2b96561c214baf2aa4a2 to your computer and use it in GitHub Desktop.
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 { 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