UNPKG

@atlaskit/editor-common

Version:

A package that contains common classes and components for editor and renderer

51 lines (49 loc) 1.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useFocus; var _react = require("react"); /** * A custom hook that handles focus on a DOM element. * Takes in a boolean value and calls element.focus * * @param {boolean} focus * * Example usage: ******************************************************************************* * const SearchBar = ({ focus }) => { * const ref = useFocus(focus); * return <input ref={ref} /> * } ******************************************************************************* * const ItemList = ({ items, focus }) => ( * <ul> * {items.map((item, index) => ( * <Item key={item.uuid} item={item} focus={focus} /> * ))} * </ul> * ); * * const Item = ({ item, focus }) => { * const ref = useFocus(focus); * return ( * <li ref={ref}> * {item.name} * </li> * ) * } ******************************************************************************* */ function useFocus(focus) { var ref = (0, _react.useRef)(null); (0, _react.useLayoutEffect)(function () { var current = ref.current; if (focus && current && document.activeElement !== current) { current.focus({ preventScroll: true }); } }, [focus]); return ref; }