UNPKG

@instructure/ui-react-utils

Version:

A React utility library made by Instructure Inc.

66 lines (64 loc) 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; exports.useDeterministicId = useDeterministicId; var _react = require("react"); var _generateId = require("@instructure/ui-utils/lib/generateId.js"); var _DeterministicIdContext = require("./DeterministicIdContext"); /* * The MIT License (MIT) * * Copyright (c) 2015 - present Instructure, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /** * A React hook that provides deterministic ID generation for functional components. * * This hook is the functional component equivalent of the `withDeterministicId` decorator. * It uses the `DeterministicIdContext` which is needed for deterministic id generation. * * The context is there for the users to pass an `instanceCounterMap` Map which is then used * in the child components to deterministically create ids for them based on the `instanceCounterMap`. * Read more about it here: [SSR guide](https://instructure.design/#server-side-rendering) * * @param componentName - Optional component name to use as the ID prefix. * @returns A function that generates deterministic IDs. The function accepts an optional instanceName parameter. * * @example * ```tsx * const MyComponent = () => { * const [deterministicId, setDeterministicId] = useState() * const getId = useDeterministicId('MyComponent') * useEffect(() => { * setDeterministicId(getId()) * }, []) * return <div id={deterministicId}>Content</div> * } * ``` */ function useDeterministicId(componentName) { const instanceCounterMap = (0, _react.useContext)(_DeterministicIdContext.DeterministicIdContext); return (instanceName = componentName) => { return (0, _generateId.generateId)(instanceName, instanceCounterMap); }; } var _default = exports.default = useDeterministicId;