Package Exports
- reakit-utils
- reakit-utils/dom
- reakit-utils/events
- reakit-utils/flatten
- reakit-utils/focus
- reakit-utils/hooks
- reakit-utils/misc
- reakit-utils/types
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (reakit-utils) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
reakit-utils
This is experimental and may have breaking changes in minor versions.
Installation
npm:
npm i reakit-utilsYarn:
yarn add reakit-utilsAPI
Table of Contents
- canUseDOM
- isUA
- getDocument
- getWindow
- getActiveElement
- contains
- isButton
- matches
- closest
- isTextField
- getNativeElementType
- isPortalEvent
- isSelfTarget
- createEvent
- fireEvent
- fireBlurEvent
- fireKeyboardEvent
- getNextActiveElementOnBlur
- flatten
- isFocusable
- isTabbable
- getAllFocusableIn
- getFirstFocusableIn
- getAllTabbableIn
- getFirstTabbableIn
- getLastTabbableIn
- getNextTabbableIn
- getPreviousTabbableIn
- getClosestFocusable
- hasFocus
- hasFocusWithin
- ensureFocus
- useSafeLayoutEffect
- useInitialValue
- useLazyRef
- useLiveRef
- useEventCallback
- useForkRef
- useNativeElementType
- useUpdateEffect
- shallowEqual
- toArray
- applyState
- isObject
- isPlainObject
- isPromise
- isEmpty
- isInteger
- removeIndexFromArray
- removeItemFromArray
- omit
- pick
- types
canUseDOM
It's true if it is running in a browser environment or false if it is not (SSR).
Examples
import { canUseDOM } from "reakit-utils";
const title = canUseDOM ? document.title : "";isUA
Checks if a given string exists in the user agent string.
Parameters
stringstring
getDocument
Returns element.ownerDocument || document.
Parameters
Returns Document
getWindow
Returns element.ownerDocument.defaultView || window.
Parameters
elementElement?
Returns Window
getActiveElement
Returns element.ownerDocument.activeElement.
Parameters
contains
Similar to Element.prototype.contains, but a little bit faster when
element is the same as child.
Parameters
Examples
import { contains } from "reakit-utils";
contains(document.getElementById("parent"), document.getElementById("child"));Returns boolean
isButton
Checks whether element is a native HTML button element.
Parameters
Examples
import { isButton } from "reakit-utils";
isButton(document.querySelector("button")); // true
isButton(document.querySelector("input[type='button']")); // true
isButton(document.querySelector("div")); // false
isButton(document.querySelector("input[type='text']")); // false
isButton(document.querySelector("div[role='button']")); // falseReturns boolean
matches
Ponyfill for Element.prototype.matches
Parameters
Returns boolean
closest
Ponyfill for Element.prototype.closest
Parameters
elementElementselectorsK
Examples
import { closest } from "reakit-utils";
closest(document.getElementById("id"), "div");
// same as
document.getElementById("id").closest("div");Returns any
isTextField
Check whether the given element is a text field, where text field is defined by the ability to select within the input, or that it is contenteditable.
Parameters
elementHTMLElement
Examples
import { isTextField } from "reakit-utils";
isTextField(document.querySelector("div")); // false
isTextField(document.querySelector("input")); // true
isTextField(document.querySelector("input[type='button']")); // false
isTextField(document.querySelector("textarea")); // true
isTextField(document.querySelector("div[contenteditable='true']")); // trueReturns boolean
getNativeElementType
Returns the native tag name of the passed element. If the element is not
provided, the second argument defaultType will be used, but only if it's
a string.
Parameters
Examples
import { getNativeElementType } from "reakit-utils";
getNativeElementType(document.querySelector("div")); // "div"
getNativeElementType(document.querySelector("button")); // "button"
getNativeElementType(null, "button"); // "button"
getNativeElementType(null, SomeComponent); // undefinedisPortalEvent
Returns true if event has been fired within a React Portal element.
Parameters
eventSyntheticEvent
Returns boolean
isSelfTarget
Returns true if event.target and event.currentTarget are the same.
Parameters
eventSyntheticEvent
Returns boolean
createEvent
Creates an event. Supports IE 11.
Parameters
elementHTMLElementtypestringeventInitEventInit?
Examples
import { createEvent } from "reakit-utils";
const element = document.getElementById("id");
createEvent(element, "blur", { bubbles: false });Returns Event
fireEvent
Creates and dispatches an event. Supports IE 11.
Parameters
elementHTMLElementtypestringeventInitEventInit
Examples
import { fireEvent } from "reakit-utils";
fireEvent(document.getElementById("id"), "blur", {
bubbles: true,
cancelable: true,
});fireBlurEvent
Creates and dispatches a blur event. Supports IE 11.
Parameters
elementHTMLElementeventInitFocusEventInit?
Examples
import { fireBlurEvent } from "reakit-utils";
fireBlurEvent(document.getElementById("id"));fireKeyboardEvent
Creates and dispatches a keyboard event. Supports IE 11.
Parameters
elementHTMLElementtypestringeventInitKeyboardEventInit
Examples
import { fireKeyboardEvent } from "reakit-utils";
fireKeyboardEvent(document.getElementById("id"), "keydown", {
key: "ArrowDown",
shiftKey: true,
});getNextActiveElementOnBlur
Cross-browser method that returns the next active element (the element that is receiving focus) after a blur event is dispatched. It receives the blur event object as the argument.
Parameters
event(ReactFocusEvent | FocusEvent)
Examples
import { getNextActiveElementOnBlur } from "reakit-utils";
const element = document.getElementById("id");
element.addEventListener("blur", (event) => {
const nextActiveElement = getNextActiveElementOnBlur(event);
});flatten
Transforms an array with multiple levels into a flattened one.
Parameters
arrayArray<T>
Examples
import { flatten } from "reakit-utils";
flatten([0, 1, [2, [3, 4], 5], 6]);
// => [0, 1, 2, 3, 4, 5, 6]isFocusable
Checks whether element is focusable or not.
Parameters
elementElement
Examples
import { isFocusable } from "reakit-utils";
isFocusable(document.querySelector("input")); // true
isFocusable(document.querySelector("input[tabindex='-1']")); // true
isFocusable(document.querySelector("input[hidden]")); // false
isFocusable(document.querySelector("input:disabled")); // falseReturns boolean
isTabbable
Checks whether element is tabbable or not.
Parameters
elementElement
Examples
import { isTabbable } from "reakit-utils";
isTabbable(document.querySelector("input")); // true
isTabbable(document.querySelector("input[tabindex='-1']")); // false
isTabbable(document.querySelector("input[hidden]")); // false
isTabbable(document.querySelector("input:disabled")); // falseReturns boolean
getAllFocusableIn
Returns all the focusable elements in container.
Parameters
containerElement
getFirstFocusableIn
Returns the first focusable element in container.
Parameters
containerElement
Returns (Element | null)
getAllTabbableIn
Returns all the tabbable elements in container, including the container
itself.
Parameters
containerElementfallbackToFocusableboolean? Iftrue, it'll return focusable elements if there are no tabbable ones.
getFirstTabbableIn
Returns the first tabbable element in container, including the container
itself if it's tabbable.
Parameters
containerElementfallbackToFocusableboolean? Iftrue, it'll return the first focusable element if there are no tabbable ones.
Returns (Element | null)
getLastTabbableIn
Returns the last tabbable element in container, including the container
itself if it's tabbable.
Parameters
containerElementfallbackToFocusableboolean? Iftrue, it'll return the last focusable element if there are no tabbable ones.
Returns (Element | null)
getNextTabbableIn
Returns the next tabbable element in container.
Parameters
containerElementfallbackToFocusableboolean? Iftrue, it'll return the next focusable element if there are no tabbable ones.
Returns (Element | null)
getPreviousTabbableIn
Returns the previous tabbable element in container.
Parameters
containerElementfallbackToFocusableboolean? Iftrue, it'll return the previous focusable element if there are no tabbable ones.
Returns (Element | null)
getClosestFocusable
Returns the closest focusable element.
Parameters
element(T | null)?containerElement
Returns (Element | null)
hasFocus
Checks if element has focus. Elements that are referenced by
aria-activedescendant are also considered.
Parameters
elementElement
Examples
import { hasFocus } from "reakit-utils";
hasFocus(document.getElementById("id"));Returns boolean
hasFocusWithin
Checks if element has focus within. Elements that are referenced by
aria-activedescendant are also considered.
Parameters
elementElement
Examples
import { hasFocusWithin } from "reakit-utils";
hasFocusWithin(document.getElementById("id"));Returns boolean
ensureFocus
Ensures element will receive focus if it's not already.
Parameters
elementHTMLElement$1EnsureFocusOptions (optional, default{})$1.preventScroll$1.isActive(optional, defaulthasFocus)
Examples
import { ensureFocus } from "reakit-utils";
ensureFocus(document.activeElement); // does nothing
const element = document.querySelector("input");
ensureFocus(element); // focuses element
ensureFocus(element, { preventScroll: true }); // focuses element preventing scroll jump
function isActive(el) {
return el.dataset.active === "true";
}
ensureFocus(document.querySelector("[data-active='true']"), { isActive }); // does nothingReturns number requestAnimationFrame call ID so it can be passed to cancelAnimationFrame if needed.
useSafeLayoutEffect
React.useLayoutEffect that fallbacks to React.useEffect on server side.
useInitialValue
Returns a value that never changes even if the argument is updated.
Parameters
valueInitialState<T>
Examples
import { useInitialValue } from "reakit-utils";
function Component({ prop }) {
const initialProp = useInitialValue(prop);
}useLazyRef
Returns a value that is lazily initiated and never changes.
Parameters
initfunction (): T
Examples
import { useLazyRef } from "reakit-utils";
function Component() {
const set = useLazyRef(() => new Set());
}useLiveRef
Creates a React.RefObject that is constantly updated with the incoming
value.
Parameters
valueT
Examples
import { useLiveRef } from "reakit-utils";
function Component({ prop }) {
const propRef = useLiveRef(prop);
}useEventCallback
Creates a memoized callback function that is constantly updated with the incoming callback.
Parameters
callbackT?
Examples
import { useEffect } from "react";
import { useEventCallback } from "reakit-utils";
function Component(props) {
const onClick = useEventCallback(props.onClick);
useEffect(() => {}, [onClick]);
}useForkRef
Merges React Refs into a single memoized function ref so you can pass it to an element.
Parameters
Examples
import { forwardRef, useRef } from "react";
import { useForkRef } from "reakit-utils";
const Component = forwardRef((props, ref) => {
const internalRef = useRef();
return <div {...props} ref={useForkRef(internalRef, ref)} />;
});useNativeElementType
Returns the native tag name of an element by parsing its ref object. If the
second argument defaultType is provided, it's going to be used by default
on the first render, before React runs the effects.
Parameters
Examples
import * as React from "react";
import { useNativeElementType } from "reakit-utils";
function Component(props) {
const ref = React.useRef();
// button on the first render, div on the second render
const type = useNativeElementType(ref, "button");
return <div ref={ref} {...props} />;
}useUpdateEffect
A React.useEffect that will not run on the first render.
Parameters
effectEffectCallbackdeps(ReadonlyArray<any> | undefined)?
shallowEqual
Compares two objects.
Parameters
aAnyObject?bAnyObject?
Examples
import { shallowEqual } from "reakit-utils";
shallowEqual({ a: "a" }, {}); // false
shallowEqual({ a: "a" }, { b: "b" }); // false
shallowEqual({ a: "a" }, { a: "a" }); // true
shallowEqual({ a: "a" }, { a: "a", b: "b" }); // falsetoArray
Transforms arg into an array if it's not already.
Parameters
argT
Examples
import { toArray } from "reakit-utils";
toArray("a"); // ["a"]
toArray(["a"]); // ["a"]applyState
Receives a setState argument and calls it with currentValue if it's a
function. Otherwise return the argument as the new value.
Parameters
argumentSetStateAction<T>currentValueT
Examples
import { applyState } from "reakit-utils";
applyState((value) => value + 1, 1); // 2
applyState(2, 1); // 2isObject
Checks whether arg is an object or not.
Parameters
argany
Returns boolean
isPlainObject
Checks whether arg is a plain object or not.
Parameters
argany
Returns boolean
isPromise
Checks whether arg is a promise or not.
Parameters
arg(T | Promise<T>)
Returns boolean
isEmpty
Checks whether arg is empty or not.
Parameters
argany
Examples
import { isEmpty } from "reakit-utils";
isEmpty([]); // true
isEmpty(["a"]); // false
isEmpty({}); // true
isEmpty({ a: "a" }); // false
isEmpty(); // true
isEmpty(null); // true
isEmpty(undefined); // true
isEmpty(""); // trueReturns boolean
isInteger
Checks whether arg is an integer or not.
Parameters
argany
Examples
import { isInteger } from "reakit-utils";
isInteger(1); // true
isInteger(1.5); // false
isInteger("1"); // true
isInteger("1.5"); // falseReturns boolean
removeIndexFromArray
Immutably removes an index from an array.
Parameters
arrayTindexnumber
Examples
import { removeIndexFromArray } from "reakit-utils";
removeIndexFromArray(["a", "b", "c"], 1); // ["a", "c"]Returns Array A new array without the item in the passed index.
removeItemFromArray
Immutably removes an item from an array.
Parameters
arrayAitemany
Examples
import { removeItemFromArray } from "reakit-utils";
removeItemFromArray(["a", "b", "c"], "b"); // ["a", "c"]
// This only works by reference
const obj = {};
removeItemFromArray([obj], {}); // [obj]
removeItemFromArray([obj], obj); // []Returns Array A new array without the passed item.
omit
Omits specific keys from an object.
Parameters
objectTpaths(ReadonlyArray<K> | Array<K>)
Examples
import { omit } from "reakit-utils";
omit({ a: "a", b: "b" }, ["a"]); // { b: "b" }Returns Omit<T, K>
pick
Picks specific keys from an object.
Parameters
objectTpaths(ReadonlyArray<K> | Array<K>)
Examples
import { pick } from "reakit-utils";
pick({ a: "a", b: "b" }, ["a"]); // { a: "a" }types
RenderProp
Render prop type
Type: function (props: P): React.ReactElement<any>
As
"as" prop
Type: React.ElementType<P>
HTMLAttributesWithRef
Type: any
ExtractHTMLAttributes
Returns only the HTML attributes inside P
type OnlyId = ExtractHTMLAttributes<{ id: string; foo: string }>;
type HTMLAttributes = ExtractHTMLAttributes<any>;Type: Pick<HTMLAttributesWithRef, Extract<any, any>>
UnionToIntersection
Transforms "a" | "b" into "a" & "b"
Type: any
PropsWithAs
Generic component props with "as" prop
Type: any
ArrayValue
Returns the type of the items in an array
Type: any
AnyFunction
Any function
Type: function (...args: Array<any>): any
AnyObject
Any object
Type: Record<any, any>
SetState
State hook setter.
Type: React.Dispatch<React.SetStateAction<T>>
InitialState
Initial state.
Type: (T | function (): T)
License
MIT © Diego Haz