1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】Refのメモ

Last updated at Posted at 2022-03-28

業務でDOMを取得する際に使用したのでメモ。

div要素を取得してみる

import { useEffect, useRef } from "react";

const Component = () => {
    const ref = useRef(null);

    useEffect(() => {
        console.log(ref.current);
    }, []);

    return (
        <div ref={ref}>hello</div>
    );
};

export default Component;

コンソールの結果は

Console
<div>hello</div>

ためしにdivの小要素を取得してみる

import { useEffect, useRef } from "react";

const Component = () => {
    const ref = useRef(null);

    useEffect(() => {
        let child = ref.current?.children;
        console.log(child);
    }, []);

    return (
        <div ref={ref}>
          <h2>タイトル01</h2>
          <p>テキスト</p>
          <h2>タイトル02</h2>
          <p>テキスト</p>
        </div>
    );
};

export default Component;

コンソールの結果は

Console
HTMLCollection {0: HTMLHeadingElement, 1: HTMLParagraphElement, 2: HTMLHeadingElement, 3: HTMLParagraphElement, length: 4…}
0: <h2>タイトル01</h2>
1: <p>テキスト</p>
2: <h2>タイトル02</h2>
3: <p>テキスト</p>

ためしにdivの小要素を取得して配列にしてみる

import { useEffect, useRef } from "react";

const Component = () => {
    const ref = useRef(null);

    useEffect(() => {
        let child = ref.current?.children;
        let elms = [].slice.call(child)
        console.log(elms);
    }, []);

    return (
        <div ref={ref}>
          <h2>タイトル01</h2>
          <p>テキスト</p>
          <h2>タイトル02</h2>
          <p>テキスト</p>
        </div>
    );
};

export default Component;

コンソールの結果は

Console
(4) [HTMLHeadingElement, HTMLParagraphElement, HTMLHeadingElement, HTMLParagraphElement]
0: <h2>タイトル01</h2>
1: <p>テキスト</p>
2: <h2>タイトル02</h2>
3: <p>テキスト</p>

最後の方は何してるのって感じですね。
公式ではRefを使いすぎるなと書いてあるので気をつけます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?