react useRef

권슬기·2023년 6월 22일
0

react

목록 보기
8/17

useRef => 리액트에서 돔을 선택하는 기능

  import {useRef, useState} from "react";

  const authorInput = useRef();
  
  const handleSubmit = () => {
    if (state.author.length < 1) {
      authorInput.current.focus();
      return;
    }
  };

	return(
    	<input
          ref={authorInput}
          name="author"
          value={state.author}
          onChange={handleChangeState}
        />
    )

1 useRef(); import하고 const 함수명을 넣어 선언해준다.
2 선택할 돔에 ref={}으로 이름을 준다
3 선택할 돔에 명령할 코드를 입력한다. 이번 코드에서는 handleSubmit 함수를 만들어서 state의 글자수가 부족한 경우 authorInput에 커서가 포커스 되도록 했다.

  • authorInput.current.focus에서 current가 붙는 이유
    현재 가르키는 값을 프로퍼티로 가져와서 사용하려고.
profile
병아리 프론트엔드 개발자

0개의 댓글

관련 채용 정보