npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@component-driven/react-focus-within

v2.0.2

Published

The missing JS API of the CSS `:focus-within` for React

Downloads

52

Readme

FocusWithin is a component that allows detecting if one of its children has focus. It can be considered as a missing JS API for focus-within.

FocusWithin will fire onFocus once one of its children will receive focus. Similarly onBlur is going to be fired once focus is left all its children.

Simple example

Open developer console to see log messages.

<FocusWithin
  onFocus={() => {
    console.log('Received focus')
  }}
  onBlur={() => {
    console.log('Lost focus')
  }}
>
  <input type="text" placeholder="Click to activate first input" />
  <input type="text" placeholder="Use Tab to activate next input" />
  <button>A button to try focus</button>
</FocusWithin>

Reacting to the focus change

If you want to react to the focus change, use function as a children pattern. When function is used as children, you must provide the ref prop.

<FocusWithin
  onFocus={() => {
    console.log('Received focus')
  }}
  onBlur={() => {
    console.log('Lost focus')
  }}
>
  {({ focused, getRef }) => (
    <form>
      <fieldset
        ref={getRef}
        style={{ borderColor: focused ? 'blue' : '#999' }}
      >
        <label htmlFor="input1">First input</label>
        <input
          id="input1"
          type="text"
          placeholder="Click to activate first input"
        />
        <label htmlFor="input2">First input</label>
        <input
          id="input2"
          type="text"
          placeholder="Use Tab to activate next input"
        />
        <button type="submit">Submit</button>
        <p style={{ color: focused ? 'danger' : 'text' }}>
          {focused ? 'Focus is inside' : 'No focus here'}
        </p>
      </fieldset>
    </form>
  )}
</FocusWithin>

Using with CSS-in-JS libs

If you're using a CSS-in-JS library like styled-components you need to pass a ref using ref prop. You can use getRef function from the parameters.

;({ focused: Boolean, getRef: Function }) => React.Element
const styled = require('styled-components').default
const StyledBox = styled('div')`
  padding: 20px;
  border: 1px solid;
  border-color: ${props =>
    props.focused ? 'palevioletred' : '#999'};

  & > * + * {
    margin-left: 20px;
  }
`
;<FocusWithin
  onFocus={() => {
    console.log('Received focus')
  }}
  onBlur={() => {
    console.log('Lost focus')
  }}
>
  {({ focused, getRef }) => (
    <StyledBox ref={getRef} focused={focused}>
      <input
        type="text"
        placeholder="Click to activate first input"
      />
      <input
        type="text"
        placeholder="Use Tab to activate next input"
      />
      <button>A button to try focus</button>
    </StyledBox>
  )}
</FocusWithin>

Note: It's recommended to use :focus-within selector instead of interpoaltions whenever possible.

Focus method

Sometimes it's needed to focus the container node programmatically. You can use the public method focus. Note that tabIndex={-1} needs to be set on non-interactive elements to make them receive focus.

const ref = React.createRef()
;<div>
  <FocusWithin ref={ref}>
    {({ focused, getRef }) => (
      <span tabIndex={-1} ref={getRef}>
        {focused ? 'Focused' : 'Not focused'}
      </span>
    )}
  </FocusWithin>
  <button
    onClick={() => {
      ref.current.focus()
    }}
  >
    Focus the span
  </button>
</div>

Naïve focus trap implementation

import { useRef, useState, useEffect } from 'react'

const firstInput = useRef(null)
const [enabled, setEnabled] = useState(false)

useEffect(() => {
  if (enabled) {
    firstInput.current.focus()
  }
}, [enabled])
;<FocusWithin
  onBlur={() => {
    enabled && firstInput.current.focus()
  }}
>
  <fieldset>
    <input
      type="text"
      placeholder="Click to activate first input"
      ref={firstInput}
    />
    <input type="text" placeholder="Use Tab to activate next input" />
    <button
      type="submit"
      onClick={() => {
        setEnabled(!enabled)
      }}
    >
      {enabled ? 'Disable' : 'Enable'} focus trap
    </button>
  </fieldset>
</FocusWithin>