react-navplus
Version:
A flexible, performance-optimized navigation link component for React with multi-router support, prefetching, and advanced active state detection
50 lines • 2.2 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useIsActive = useIsActive;
const react_1 = require("react");
const matchers_1 = require("../utils/matchers");
/**
* Hook for determining if a link is active based on the current location,
* with support for custom matching functions and strategies.
*
* @param {string} to - The target URL for the link
* @param {object} options - Options for determining active state
* @param {object} options.location - Location object with pathname
* @param {MatchMode} options.matchMode - How to match the URL ('exact', 'startsWith', 'includes', 'pattern')
* @param {RegExp} options.matchPattern - Custom regex pattern for matching
* @param {string} options.customActiveUrl - Custom URL to use for active state detection
* @param {Function} options.isActiveFunc - Custom active detection function
* @returns {boolean} - Whether the link is active
*
* @example
* // Basic usage with location from React Router
* const location = useLocation();
* const isActive = useIsActive('/home', { location });
*
* @example
* // With custom match mode
* const isActive = useIsActive('/dashboard', {
* location,
* matchMode: 'exact'
* });
*
* @example
* // With custom function
* const isActive = useIsActive('/products', {
* location,
* isActiveFunc: (pathname, url) => pathname.includes(url) && pathname.includes('category')
* });
*/
function useIsActive(to, options = {}) {
const { location, matchMode = 'includes', matchPattern, customActiveUrl, isActiveFunc } = options;
return (0, react_1.useMemo)(() => {
if (!(location === null || location === void 0 ? void 0 : location.pathname))
return false;
const urlToMatch = customActiveUrl || to;
if (isActiveFunc) {
return (0, matchers_1.isActiveWithCustomFn)(location.pathname, urlToMatch, isActiveFunc);
}
return (0, matchers_1.isActive)(location.pathname, urlToMatch, matchMode, matchPattern);
}, [location === null || location === void 0 ? void 0 : location.pathname, to, matchMode, matchPattern, customActiveUrl, isActiveFunc]);
}
//# sourceMappingURL=useIsActive.js.map