😊

useRefを使ってDOM操作を行う

2023/03/16に公開

How to

useRef フックは、current という単一のプロパティを持つオブジェクトを返します。
最初は、myRef.currentnull になります。 React がこの <div> の DOM ノードを作成すると、React はこのノードへの参照を myRef.current に入れます。
その後、イベント ハンドラーからこの DOM ノードにアクセスし、そこに定義されている組み込みのブラウザー API を使用できます。

import { useRef } from "react";

export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>Focus the input</button>
    </>
  );
}

<input ref={inputRef}> として渡します。これは、この <input> の DOM ノードを inputRef.current に入れるように React に指示します。
React の DOM ノードにアクセスできることが useRef の最も一般的な使い方です。

GitHubで編集を提案

Discussion