useRef - 돔을 조작하는 예시 / 이미지 스크롤

piper ·2024년 2월 14일
0

React

목록 보기
9/22

버튼을 클릭하면 해당 이미지로 스크롤되는 것은 돔을 조작하는 것이다.
이를 구현해보다가 만들어낸 오류이다.

import React from "react";
import { useRef } from "react";

const ScrollingAnImage = () => {
  const listRef = useRef(null);

  const scroll = (i) => {
    const List = listRef.current;
    const Img = List.querySelectorAll("li> img")[i];
    Img.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "center",
    });
  };

  return (
    <>
      <nav>
        <button onClick={scroll}>Tom</button>
        <button onClick={scroll}>Maru</button>
        <button onClick={scroll}>Jelly</button>
      </nav>
      <div>
        <ul ref={listRef}>
          <li>
            <img src="https://placekitten.com/g/200/200" alt="Tom" />
          </li>
          <li>
            <img src="https://placekitten.com/g/300/200" alt="Maru" />
          </li>
          <li>
            <img src="https://placekitten.com/g/250/200" alt="Jellylorum" />
          </li>
        </ul>
      </div>
    </>
  );
};

export default ScrollingAnImage;

element.scrollIntoView
오류 해결 과정: Element (en-US) 인터페이스의 scrollIntoView() 메소드는 scrollIntoView()가 호출 된 요소가 사용자에게 표시되도록 요소의 상위 컨테이너를 스크롤합니다.

const element = document.getElementById("box");

element.scrollIntoView();
element.scrollIntoView(false);
element.scrollIntoView({ block: "end" });
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });

1) Ul이 아닌 Li 에 ref를 달아주어보았다. 같은 오류 발생
2) 다시 보니 함수의 파라미터가 전달되지 않았다.

 const scroll = (i) => {
    const List = listRef.current;
    const Img = List.querySelectorAll("li> img")[i];
    Img.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "center",
    });
  };
  
  <nav>
        <button onClick={scroll(0)}>Tom</button>
        <button onClick={scroll(1)}>Maru</button>
        <button onClick={scroll(2)}>Jelly</button>
      </nav>

위와 같은 식으로 호출해주면 scroll 함수가 즉시 호출되기 때문에 랜더링이 완료되지
못한다. 따라서 화살표 함수로 바꾸어주어야 한다.

완성된 코드:

import React from "react";
import { useRef } from "react";

const ScrollingAnImage = () => {
  const listRef = useRef(null);

  const scroll = (i) => {
    const List = listRef.current;
    const Img = List.querySelectorAll("li> img")[i];
    Img.scrollIntoView({
      behavior: "smooth",
      block: "nearest",
      inline: "center",
    });
  };

  return (
    <>
      <nav>
        <button
          onClick={() => {
            scroll(0);
          }}
        >
          Tom
        </button>
        <button
          onClick={() => {
            scroll(1);
          }}
        >
          Maru
        </button>
        <button
          onClick={() => {
            scroll(2);
          }}
        >
          Jelly
        </button>
      </nav>
      <div>
        <ul ref={listRef}>
          <li>
            <img src="https://placekitten.com/g/200/200" alt="Tom" />
          </li>
          <li>
            <img src="https://placekitten.com/g/300/200" alt="Maru" />
          </li>
          <li>
            <img src="https://placekitten.com/g/250/200" alt="Jellylorum" />
          </li>
        </ul>
      </div>
    </>
  );
};

export default ScrollingAnImage;
profile
연습일지

0개의 댓글