안녕하세요

초보 코더입니다.

 

이번에는 useRef를 알아볼건데요.

코드는 아래와 같습니다.

 

import React, { useRef } from "react";

export default () => {
  const potato = useRef();
  setTimeout(() => potato.current.focus(), 5000);
  return (
    <>
      <div>hello</div>
      <input ref={potato} placeholder="what your name"></input>
    </>
  );
};

potato 변수에 useRef를 사용하고.

input 태그에 ref를 연결해줍니다.

(useRef는 document.querySelector()와 같습니다.

 

potato 변수 밑에 setTimeout 함수를 넣어서 potato(input태그)가 5초뒤에 포커스 되는 것을 넣었습니다.

 

렌더링 시작 후 input 태그에 focus가 없지만 5초뒤에는?!

 

 

자동으로 포커스가 됩니다!!

 

쉽죠!?

+ Recent posts