프론트엔드/React

useEffect 사용 예시

거북목을 가진 김기린 2024. 4. 18. 14:32
728x90
반응형

문제

FocusableInput 컴포넌트의 첫 번째 렌더링 때, props로 넘겨 받은 shouldFocus가 true라면

FocusableInput 컴포넌트의 input 요소가 포커스를 받도록 설정해야 했음

해결

useRef를 통해 input 요소를 참조하고 useEffect의존성 배열을 빈 배열로 만들어,

첫 번째 렌더링 시에만 shoudFocus가 true일 때 포커스를 만들게 했음

코드

import React, {useEffect, useRef} from 'react';
import { createRoot } from 'react-dom/client';

const FocusableInput = ({shouldFocus}) => {
  const inputRef = useRef(null);

  useEffect(() => {
      if(shouldFocus) inputRef.current.focus();
  }, [shouldFocus])
  
  return <input ref={inputRef} />;
};

document.body.innerHTML = "<div id='root'></div>";
const root = createRoot(document.getElementById("root"));
root.render(<FocusableInput shouldFocus={true} />);
setTimeout(() => console.log(document.getElementById("root").innerHTML), 300);

 

728x90
반응형