How do you set focus on an input field after a React or Vue component renders? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you set focus on an input field after a React or Vue component renders?

message-square
0

To set focus on an input field after a React or Vue component renders, obtain a reference to the underlying DOM input element (useRef in React, or a ref / useTemplateRef in Vue) and invoke inputEl.focus({ preventScroll }) inside a post-render lifecycle hook (useEffect in React, or onMounted / nextTick in Vue)—rather than calling .focus() directly during render, which runs before DOM nodes exist or before state/DOM updates finish painting.


1. Focusing an Input After Render in React (useRef + useEffect / flushSync)

In React, attach a ref to the <input> element, call .focus() inside useEffect (on mount or when a condition changes), and guard against null refs or disabled/hidden inputs:

// React example: Focus an input on mount or when shouldFocus becomes true
import React, { useEffect, useRef } from "react";

function focusElementSafely(element, { preventScroll = false } = {}) {
  if (!(element instanceof HTMLElement)) {
    return false;
  }
  if ("disabled" in element && element.disabled) {
    return false;
  }
  if (element instanceof HTMLInputElement && element.type === "hidden") {
    return false;
  }
  if (element.getClientRects().length === 0) {
    return false;
  }

  try {
    element.focus({ preventScroll });
    return document.activeElement === element;
  } catch (error) {
    console.error(`Failed focusing element in React: ${error.message}`);
    return false;
  }
}

export function SearchBox({ shouldFocus = true, preventScroll = false }) {
  const inputRef = useRef(null);

  useEffect(() => {
    if (!shouldFocus) {
      return;
    }

    const rafId = requestAnimationFrame(() => {
      focusElementSafely(inputRef.current, { preventScroll });
    });

    return () => cancelAnimationFrame(rafId);
  }, [shouldFocus, preventScroll]);

  return <input ref={inputRef} type="search" placeholder="Search records..." />;
}
  • Never call inputRef.current?.focus() directly in the component render body: Render must stay pure and runs before the DOM node is attached.
  • Cancel pending requestAnimationFrame or timers in useEffect cleanup: Prevents focusing unmounted or stale inputs if the component unmounts quickly.

2. Focusing an Input After Render in Vue (ref / useTemplateRef + onMounted / nextTick)

In Vue 3 (<script setup>), declare a template ref (ref(null) or useTemplateRef("searchInput")), call .focus() inside onMounted for initial render or after await nextTick() when focusing a newly revealed or conditional input:

<!-- Vue 3 (<script setup>) example: Focus on mount and after conditional reveal -->
<script setup>
import { ref, onMounted, nextTick } from "vue";

const isEditing = ref(false);
const titleInput = ref(null);

function focusInputNode(el, { preventScroll = false } = {}) {
  if (!(el instanceof HTMLElement)) {
    return false;
  }
  if ("disabled" in el && el.disabled) {
    return false;
  }
  if (el instanceof HTMLInputElement && el.type === "hidden") {
    return false;
  }
  if (el.getClientRects().length === 0) {
    return false;
  }

  try {
    el.focus({ preventScroll });
    return document.activeElement === el;
  } catch (error) {
    console.error(`Failed focusing input in Vue: ${error.message}`);
    return false;
  }
}

onMounted(() => {
  focusInputNode(titleInput.value);
});

async function enableEditMode() {
  if (typeof isEditing.value !== "boolean") {
    throw new TypeError("Expected isEditing.value to be a boolean.");
  }

  try {
    isEditing.value = true;
    await nextTick();
    focusInputNode(titleInput.value);
  } catch (error) {
    console.error(`Failed focusing input after nextTick: ${error.message}`);
  }
}
</script>

<template>
  <input
    ref="titleInput"
    type="text"
    :readonly="!isEditing"
    placeholder="Document title"
  />
  <button type="button" @click="enableEditMode">Edit</button>
</template>
  • Await nextTick() after state changes before reading template refs: Reactive DOM updates flush asynchronously after reactive state mutates.
  • Remember that v-if unmounts/remounts the node while v-show toggles display: none: With v-show, wait until display is visible (getClientRects().length > 0) before expecting keyboard focus to succeed.

3. Conditional Rendering, Modals, and Autofocus Caveats

When inputs live inside modals/drawers, tabs, or conditionally mounted forms, watch out for these practical traps:

  • Prefer lifecycle/post-render focus over HTML autofocus on dynamic views: Browsers often honor autofocus only on initial page load rather than when a component mounts or opens later via client state.
  • Avoid focusing hidden (display: none) or disabled inputs: Browsers ignore .focus() on non-focusable or non-rendered elements.
  • Keep focus tracking explicit when managing multiple dynamic inputs: Store element references in a Map (keyed by field ID or item key) rather than mutating shared variables across rows.