FocusRing

A utility component that applies a CSS class when an element has keyboard focus. Focus rings are visible only when the user is interacting with a keyboard, not with a mouse, touch, or other input methods.

installyarn add @react-aria/focus
version3.3.0
usageimport {FocusRing} from '@react-aria/focus'

Introduction#


FocusRing is a utility component that can be used to apply a CSS class when an element has keyboard focus. This helps keyboard users determine which element on a page or in an application has keyboard focus as they navigate around. Focus rings are only visible when interacting with a keyboard so as not to distract mouse and touch screen users. When we are unable to detect if the user is using a mouse or touch screen, such as switching in from a different tab, we show the focus ring.

If CSS classes are not being used for styling, see useFocusRing for a hooks version.

Props#


NameTypeDefaultDescription
childrenReactElementChild element to apply CSS classes to.
focusClassstringCSS class to apply when the element is focused.
focusRingClassstringCSS class to apply when the element has keyboard focus.
withinbooleanfalseWhether to show the focus ring when something inside the container element has focus (true), or only if the container itself has focus (false).
isTextInputbooleanWhether the element is a text input.
autoFocusbooleanWhether the element will be auto focused.

Example#


This example shows how to use <FocusRing> to apply a CSS class when keyboard focus is on a button.

.button {
  -webkit-appearance: none;
  appearance: none;
  background: green;
  border: none;
  color: white;
  font-size: 14px;
  padding: 4px 8px;
}

.button.focus-ring {
  outline: 2px solid dodgerblue;
  outline-offset: 2px;
}
.button {
  -webkit-appearance: none;
  appearance: none;
  background: green;
  border: none;
  color: white;
  font-size: 14px;
  padding: 4px 8px;
}

.button.focus-ring {
  outline: 2px solid dodgerblue;
  outline-offset: 2px;
}
.button {
  -webkit-appearance: none;
  appearance: none;
  background: green;
  border: none;
  color: white;
  font-size: 14px;
  padding: 4px 8px;
}

.button.focus-ring {
  outline: 2px solid
    dodgerblue;
  outline-offset: 2px;
}
<FocusRing focusRingClass="focus-ring">
  <button className="button">Test</button>
</FocusRing>
<FocusRing focusRingClass="focus-ring">
  <button className="button">Test</button>
</FocusRing>
<FocusRing focusRingClass="focus-ring">
  <button className="button">
    Test
  </button>
</FocusRing>