Skip to content

🅰 A React hook for focusing elements and their children conditionally

License

Notifications You must be signed in to change notification settings

accessible-ui/use-conditional-focus

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation


useConditionalFocus()

Bundlephobia Code coverage Build status NPM Version MIT License

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

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 (
    <div>
      <div ref={ref}>
        // This button will be focused when `visible` is true
        <button onClick={() => setVisible(false)}>Close me</button>
      </div>
      <button onClick={() => setVisible(true)}>Click me</button>
    </div>
  )
}

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 {includeRoot: false, preventScroll: false} No See UseConditionalFocusOptions.

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

About

🅰 A React hook for focusing elements and their children conditionally

Resources

License

Stars

Watchers

Forks

Packages

No packages published