Accessing DOM Elements

Focus an Input

Example

useRef returns an object { current }. Pass it as the ref attribute and React puts the DOM element in current.

import { useRef } from 'react';

export default function App() {
  const inputRef = useRef(null);
  return (
    <div>
      <input ref={inputRef} placeholder="Your name" />
      <button onClick={() => inputRef.current.focus()}>Focus input</button>
    </div>
  );
}

Result