https://github.com/accessible-ui/use-conditional-focus
🅰 A React hook for focusing elements and their children conditionally
https://github.com/accessible-ui/use-conditional-focus
Last synced: 4 months ago
JSON representation
🅰 A React hook for focusing elements and their children conditionally
- Host: GitHub
- URL: https://github.com/accessible-ui/use-conditional-focus
- Owner: accessible-ui
- License: mit
- Created: 2019-12-16T13:59:06.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T02:21:23.000Z (over 2 years ago)
- Last Synced: 2025-01-29T22:44:54.439Z (4 months ago)
- Language: TypeScript
- Homepage:
- Size: 2.52 MB
- Stars: 1
- Watchers: 2
- Forks: 1
- Open Issues: 16
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
useConditionalFocus()
npm i @accessible/use-conditional-focus
A React hook that will focus elements conditionally. By default this will focus on the first focusable
child of the provided root element, but you can optionally include the root as well.## Quick Start
```jsx harmony
import * as React from 'react'
import useConditionalFocus from '@accessible/use-conditional-focus'const Component = () => {
const ref = React.useRef(null)
const [visible, setVisible] = React.useState(false)
// Focuses the first focusable child in the `ref` element when
// visible is `true`
useConditionalFocus(ref, visible)return (
// This button will be focused when `visible` is true
setVisible(false)}>Close me
setVisible(true)}>Click me
)
}
```## API
### useConditionalFocus(target, shouldFocus, options?)
#### Arguments
| Prop | Type | Default | Required? | Description |
| ----------- | ---------------------------------------------------------------------------------------- | -------------------------------------------- | --------- | ------------------------------------------------------------------------------ |
| target |React.RefObject<T> | T | Window | Document | null
| | Yes | A React ref, element, `window`, or `document` |
| shouldFocus | `boolean` | `false` | Yes | Provide a `true` value here to focus the first focusable child in the element. |
| options | [`UseConditionalFocusOptions`](#useconditonalfocusoptions) | `{includeRoot: false, preventScroll: false}` | No | See [`UseConditionalFocusOptions`](#useconditonalfocusoptions). |#### `UseConditonalFocusOptions`
| Prop | Type | Default | Required? | Description |
| ------------- | --------- | ------- | --------- | -------------------------------------------------------------------------------------------------------------------- |
| includeRoot | `boolean` | `false` | No | When `true` this will try to focus on the root element in addition to its children. |
| preventScroll | `boolean` | `false` | No | When `true` this will prevent your browser from scrolling the document to bring the newly-focused element into view. |#### Returns `void`
## LICENSE
MIT