@instructure/ui-react-utils

  • Version 11.7.8
  • Published
  • 260 kB
  • 8 dependencies
  • MIT license

Install

npm i @instructure/ui-react-utils
yarn add @instructure/ui-react-utils
pnpm add @instructure/ui-react-utils

Overview

A React utility library made by Instructure Inc.

Index

Variables

variable DeterministicIdContext

const DeterministicIdContext: React.Context<DeterministicIdProviderValue>;
  • Deprecated

    This context is no longer consumed by the id generation utilities and has no effect. It is retained only for backwards compatibility and will be removed in the next major version.

Functions

function callRenderProp

callRenderProp: <P extends Record<string, unknown>>(
value: Renderable<P>,
props?: P
) => any;
  • --- category: utilities/react --- Evaluate a provided value to create a renderable React element. callRenderProp

    Parameter value

    Parameter props

function DeterministicIdContextProvider

DeterministicIdContextProvider: ({
children,
instanceCounterMap,
}: React.PropsWithChildren<{
instanceCounterMap?: DeterministicIdProviderValue;
}>) => any;
  • --- category: components/contexts --- WARNING: providing the instanceCounterMap prop will result in unexpected behaviour. DO NOT USE IT!

    DEPRECATED: the instanceCounterMap prop is deprecated. You don't need to supply the instanceCounterMap to the component. It handles it internally.

    This utility component is for wrapping components with DeterministicIdContext.Provider See detailed documentation about how to use it: [InstUISettingsProvider](/#InstUISettingsProvider)

function ensureSingleChild

ensureSingleChild: (
child: ReactNode,
props?: {}
) => import('@emotion/react/jsx-runtime').JSX.Element | null;
  • --- category: utilities/react ---

    Ensure a single child. If it is a child of length 1, return a cloned instance of the child. If it is a child of length > 1, wrap in a span and return the child. Return null if child has no length. ensureSingleChild

    Parameter child

    Parameter props

    props for child

    Returns

    cloned instance for a single child, or children wrapped in a span

function getDisplayName

getDisplayName: (ReactComponent: string | ComponentType) => string;
  • --- category: utilities/react --- Get the displayName of a React component. needs a babel plugin to work https://github.com/facebook/react/issues/4915 !! getDisplayName

    Parameter ReactComponent

    Returns

    the component displayName

function getElementType

getElementType: <T extends PropsObject>(
Component: ComponentClass<T>,
props: T,
getDefault?: () => AsElementType<T>
) =>
| 'a'
| 'abbr'
| 'address'
| 'animate'
| 'animateMotion'
| 'animateTransform'
| 'area'
| 'article'
| 'aside'
| 'audio'
| 'b'
| 'base'
| 'bdi'
| 'bdo'
| 'big'
| 'blockquote'
| 'body'
| 'br'
| 'button'
| 'canvas'
| 'caption'
| 'center'
| 'circle'
| 'cite'
| 'clipPath'
| 'code'
| 'col'
| 'colgroup'
| 'data'
| 'datalist'
| 'dd'
| 'defs'
| 'del'
| 'desc'
| 'details'
| 'dfn'
| 'dialog'
| 'div'
| 'dl'
| 'dt'
| 'ellipse'
| 'em'
| 'embed'
| 'feBlend'
| 'feColorMatrix'
| 'feComponentTransfer'
| 'feComposite'
| 'feConvolveMatrix'
| 'feDiffuseLighting'
| 'feDisplacementMap'
| 'feDistantLight'
| 'feDropShadow'
| 'feFlood'
| 'feFuncA'
| 'feFuncB'
| 'feFuncG'
| 'feFuncR'
| 'feGaussianBlur'
| 'feImage'
| 'feMerge'
| 'feMergeNode'
| 'feMorphology'
| 'feOffset'
| 'fePointLight'
| 'feSpecularLighting'
| 'feSpotLight'
| 'feTile'
| 'feTurbulence'
| 'fieldset'
| 'figcaption'
| 'figure'
| 'filter'
| 'footer'
| 'foreignObject'
| 'form'
| 'g'
| 'h1'
| 'h2'
| 'h3'
| 'h4'
| 'h5'
| 'h6'
| 'head'
| 'header'
| 'hgroup'
| 'hr'
| 'html'
| 'i'
| 'iframe'
| 'image'
| 'img'
| 'input'
| 'ins'
| 'kbd'
| 'keygen'
| 'label'
| 'legend'
| 'li'
| 'line'
| 'linearGradient'
| 'link'
| 'main'
| 'map'
| 'mark'
| 'marker'
| 'mask'
| 'menu'
| 'menuitem'
| 'meta'
| 'metadata'
| 'meter'
| 'mpath'
| 'nav'
| 'noindex'
| 'noscript'
| 'object'
| 'ol'
| 'optgroup'
| 'option'
| 'output'
| 'p'
| 'param'
| 'path'
| 'pattern'
| 'picture'
| 'polygon'
| 'polyline'
| 'pre'
| 'progress'
| 'q'
| 'radialGradient'
| 'rect'
| 'rp'
| 'rt'
| 'ruby'
| 's'
| 'samp'
| 'script'
| 'search'
| 'section'
| 'select'
| 'set'
| 'slot'
| 'small'
| 'source'
| 'span'
| 'stop'
| 'strong'
| 'style'
| 'sub'
| 'summary'
| 'sup'
| 'svg'
| 'switch'
| 'symbol'
| 'table'
| 'tbody'
| 'td'
| 'template'
| 'text'
| 'textPath'
| 'textarea'
| 'tfoot'
| 'th'
| 'thead'
| 'time'
| 'title'
| 'tr'
| 'track'
| 'tspan'
| 'u'
| 'ul'
| 'use'
| 'var'
| 'video'
| 'view'
| 'wbr'
| 'webview'
| ComponentClass<any, any>
| ComponentClass<T, any>
| import('react').FunctionComponent<any>
| import('react').FunctionComponent<T>
| NonNullable<T['as']>;
  • --- category: utilities/react --- Get the React element type for a component. It uses the following logic: 1. type defined by the as prop 2. type returned by the getDefault() parameter 3. <a> if it has a href or to prop 4. <button> if it has an onClick prop 5. the component's defaultProp's as field 6. <span> if none of the above

    getElementType

    Parameter Component

    Parameter props

    Parameter getDefault

    an optional function that returns the default element type

    Returns

    the element type

function getInteraction

getInteraction: ({
props,
interactionTypes,
}?: GetInteractionOptions) => InteractionType;
  • --- category: utilities/react --- Parse the component props for the interaction type. It will return one of 'enabled', 'disabled', or 'readonly'. This is useful for form elements where consumers are able to either use the interaction prop as specified or the native html disabled or readonly attributes getInteraction

    Parameter args

    extra arguments

    Returns

    The calculated interaction type

function matchComponentTypes

matchComponentTypes: <Type extends ReactElement = ReactElement>(
componentInstance: ReactNode,
types?: string[] | ComponentType[] | ComponentType<any>[]
) => componentInstance is Type;
  • --- category: utilities/react --- Check if a React component instance (React element) matches one of the specified types.

    matchComponentTypes

    Parameter componentInstance

    Parameter types

    an array of React components

    Returns

    true if the component matches at least one of the types

function omitProps

omitProps: <T extends Record<string, any>>(
props: T,
propsToOmit?: Record<string, any> | string[],
exclude?: string[]
) => Record<string, any>;
  • --- category: utilities/react --- Return an object with the remaining props after the given props are omitted.

    Automatically excludes the following props: theme, children, className, style, styles, makeStyles, themeOverride, deterministicId omitProps

    Parameter props

    The object to process

    Parameter propsToOmit

    list disallowed prop keys or an object whose keys will be omitted. If not specified the automatically excluded props will be removed.

    Parameter exclude

    an optional array of disallowed prop names to omit

    Returns

    props object without the excluded props omitProps

function passthroughProps

passthroughProps: <P extends Record<string, unknown>>(
props: P
) => Record<string, unknown>;
  • Removes disallowed keys from the given object. Allowed keys: Valid props for HTML or SVG elements (see https://github.com/emotion-js/emotion/tree/main/packages/is-prop-valid)

    Disallowed is anything else and 'style', 'styles', 'className', 'children', 'makeStyles', 'deterministicId'

    Parameter props

    The props to process

function pickProps

pickProps: <T extends Record<string, any>>(
props: T,
propTypesOrAllowedPropList: Record<string, any> | string[],
include?: string[]
) => Record<string, unknown>;
  • --- category: utilities/react --- Return a props object with only specified propTypes.

    Parameter props

    React component props

    Parameter propTypesOrAllowedPropList

    React component propTypes or the list of allowed prop keys

    Parameter include

    an optional array of prop names to include

    Returns

    props object with only the included props pickProps

function safeCloneElement

safeCloneElement: <
E extends ReactElement<any> = ReactElement,
P extends GetProps<E> = GetProps<E>
>(
element: { ref?: any } & E,
props: { style?: any } & Partial<Attributes> & Partial<P>,
...children: ReactNode[]
) => E;
  • --- category: utilities/react --- Clones a React element without overwriting refs.

    Parameter element

    The element to clone

    Parameter props

    Props of the element

    Parameter children

function useDeterministicId

useDeterministicId: (componentName: string) => (instanceName?: string) => string;
  • A React hook that provides SSR-safe, hydration-stable ID generation for functional components.

    This hook is the functional component equivalent of the withDeterministicId decorator. It is backed by React's built-in , which produces the same id on the server and the client for a given position in the React tree.

    The returned function may be called multiple times with distinct instanceName values to derive several unique, stable ids from the same component instance (e.g. one for an input and one for its messages).

    Note: for apps that mount more than one independent React root on the same page (including module federation), pass a distinct identifierPrefix to each createRoot/hydrateRoot call so ids stay unique across roots.

    Read more about it here: [SSR guide](https://instructure.design/#server-side-rendering)

    Parameter componentName

    Component name used as a human-readable id prefix.

    Returns

    A function that generates stable ids. It accepts an optional instanceName used as the prefix for that specific id.

    Example 1

    const MyComponent = () => {
    const getId = useDeterministicId('MyComponent')
    const id = getId()
    const messagesId = getId('MyComponent-messages')
    return <div id={id} aria-describedby={messagesId}>Content</div>
    }

function windowMessageListener

windowMessageListener: (...args: unknown[]) => (ComposedComponent: any) => any;
  • --- category: utilities/react --- A decorator or higher order component that provides methods for cross-origin communication (between iframes/windows).

    see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage windowMessageListener

    Parameter messageHandler

    a handler for messages receieved by the component

    Parameter validSource

    an optional function that would restrict message handling to a specified source.

    Returns

    {Function} a function that decorates a React component with the behavior

function withDeterministicId

withDeterministicId: (
...args: unknown[]
) => (ComposedComponent: ComponentClass<any>) => any;
  • This decorator injects a deterministicId prop into the decorated class, used to generate SSR-safe, hydration-stable ids.

    It is backed by React's built-in , which produces the same id on the server and the client for a given position in the React tree The injected deterministicId(instanceName?) function may be called multiple times with distinct instanceName values to derive several unique, stable ids from the same component instance.

    Note: for apps that mount more than one independent React root on the same page (including module federation), pass a distinct identifierPrefix to each createRoot/hydrateRoot call so ids stay unique across roots. Read more about it here: [SSR guide](https://instructure.design/#server-side-rendering)

Type Aliases

type DeterministicIdProviderValue

type DeterministicIdProviderValue = Map<string, number>;

    type GetInteractionOptions

    type GetInteractionOptions = {
    props?: {
    /**
    * specifies the interaction mode, one of 'enabled', 'disabled', or 'readonly'
    */
    interaction?: InteractionType | null;
    /**
    * specifies if the component is disabled. Will take precedence over readOnly
    */
    disabled?: boolean | null;
    /**
    * specifies if the component is readonly
    */
    readOnly?: boolean | null;
    [key: string]: any;
    };
    /**
    * an array specifying the interaction types available to the component, ['disabled', 'readonly'] by default
    */
    interactionTypes?: InteractionType[];
    };

      type InteractionType

      type InteractionType = 'enabled' | 'disabled' | 'readonly';

        type WithDeterministicIdProps

        type WithDeterministicIdProps = {
        deterministicId?: (instanceName?: string) => string;
        };

          Package Files (16)

          Dependencies (8)

          Dev Dependencies (3)

          Peer Dependencies (2)

          Badge

          To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

          You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@instructure/ui-react-utils.

          • Markdown
            [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@instructure/ui-react-utils)
          • HTML
            <a href="https://www.jsdocs.io/package/@instructure/ui-react-utils"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>