Auto focus
Moves focus to an element when it appears, such as an error summary after a form is submitted.
Used by govuk-react's error summary and notification banner.
Unstyled
The primitive on plain elements, with no GOV.UK markup or styles: what you start from in your own library.
Code
<AutoFocus.Root>
<AutoFocus.Target role="alert">
<h2>There is a problem</h2>
<a href="#full-name">Enter your full name</a>
</AutoFocus.Target>
</AutoFocus.Root>In govuk-react
govuk-react's error summary, built with this primitive.
Code
<ErrorSummary.Composite {...args} disableAutoFocus={viewMode === 'docs'} />Usage
import * as AutoFocus from '@govuk-react/primitives/auto-focus';
<AutoFocus.Root>
<AutoFocus.Target role="alert">There is a problem</AutoFocus.Target>
</AutoFocus.Root>;
Moves focus to Target when it appears, such as an error summary after a form is submitted. The server renders the target with tabindex="-1" and autofocus, so the browser focuses it when the page loads, even without JavaScript. As in govuk-frontend, the target loses its tabindex once focus moves on. Pass disabled to Root to leave focus alone, or to Target in an island without a Root.
Inline script
To make the markup interactive before React hydrates, inline @govuk-react/primitives/inline/auto-focus-element.js, or render it from React on the server:
import { InlineScript, autoFocus } from '@govuk-react/primitives/inline-script';
<InlineScript script={autoFocus} nonce={nonce} />;API reference
AutoFocus.Root
| Prop | Type |
|---|---|
disabledDon't move focus. | boolean |
AutoFocus.Target
What gets focus.
| Prop | Type |
|---|---|
asChildRender the only child instead, with this part's props merged onto it. | boolean |
disabledDon't move focus. Defaults to Root's. | boolean |