useRef로 DOM 조작 - input element의 focus

soo's·2023년 4월 11일
0

React Study

목록 보기
8/14
post-thumbnail

0. 구현하고 싶은 부분

사용자의 입력 값의 최소 길이를 정해 놓고 그 길이 미만일 경우 사용자가 값을 입력하게끔 하고 싶다. 이 부분을 Alert()로 만들 수도 있지만, 사용자가 입력 후 경고창으로 메시지를 노출하기보다 좀 더 유연하게 피드백을 줄 수 있는 것이 focus라고 생각한다. 따라서 이 부분을 alert()가 아닌 input element의 focus로 컨트롤 해보자.

1. useRef 사용

// DiaryEditor.js
const DiaryEditor = () => {
  // useRef로 React.MutableRefObject 객체 authorInput에 담기
  const authorInput = useRef();
  ...중략
  
  // submit 컨트롤하는 함수
  const handleSubmit = () => {
    if (state.author.length < 1) {
      // 작성자 길이 짧음
      console.log(authorInput);
    }
    ... 중략
  };
  return (
    <div className="DiaryEditor">
      <h2>Diary</h2>
      <div>
        <input ref={authorInput} name="author" value={state.author} onChange={handleChangeState}></input>
      </div>
      ...중략
    </div>
  );
};

useRef hook을 사용해서 authorInput에 React.MutableRefObj를 담고, authorInput를 콘솔에 찍어보면 아래와 같다.

ref={authorInput}를 연결해 놓은 element가 찍히게 되는데, 그 current 값이 현재 input이다. 따라서 current인 input의 메서드들이 좌르륵 나온다. 따라서 나는 사용자의 input 입력 값이 너무 짧을때, 그 길이에 따라서 input element의 focus를 조작하기 위해 useRef() hook을 사용하는 것이다.


const handleSubmit = () => {
    if (state.author.length < 1) {
      // 작성자 길이 짧음 -> inpuf focus
      authorInput.current.focus();
      return;
    }
    if (state.content.length < 5) {
      // 컨텐츠 길이 짧음 -> textarea focus
      contentInput.current.focus();
      return;
    }
  };

이렇게 author(작성자 입력 칸)의 길이가 1보다 작을 때, useRef를 이용해서 authorInput.current.focus() 함수를 호출하고 리턴하며, 같은 로직으로 content(다이어리 입력 칸)도 새로운 useRef를 이용해서 contentInput.current.focus()을 만들어서 사용해준다.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN