npm install @solid-primitives/autofocus
yarn add @solid-primitives/autofocus
pnpm add @solid-primitives/autofocus


Primitives for autofocusing HTML elements.

The native autofocus attribute only works on page load, which makes it incompatible with SolidJS. These primitives run on render, allowing autofocus on initial render as well as dynamically added components.

  • autofocus - Directive to autofocus an element on render.
  • createAutofocus - Reactive primitive to autofocus an element on render.


#How to use it

The autofocus directive uses the native autofocus attribute to determine it should focus the element or not. Using this directive without autofocus={true} (or the shorthand autofocus) will not perform anything.

As a directive:

import { autofocus } from "@solid-primitives/autofocus";
// prevents from being tree-shaken by TS

<button use:autofocus autofocus>

// Autofocus directive can be disabled if `false` is passed as option
<button use:autofocus={false} autofocus>
  Not Autofocused

Or with ref

import { autofocus } from "@solid-primitives/autofocus";

<button ref={autofocus} autofocus>


createAutofocus reactively autofocuses an element passid in as a signal.

import { createAutofocus } from "@solid-primitives/autofocus";

// Using ref
let ref!: HTMLButtonElement;
createAutofocus(() => ref);

<button ref={ref}>Autofocused</button>;

// Using ref signal
const [ref, setRef] = createSignal<HTMLButtonElement>();

<button ref={setRef}>Autofocused</button>;


Live Site

You may see the working example here:

Source code: