🧠 지식창고/기능

[React] input 태그에 focus 이벤트 사용하기

은돌1113 2022. 3. 10. 18:26
728x90
 

antd Input 태그에 focus 이벤트 사용하기

React 앱에서 antd의 Input 컴포넌트를 사용하고 있을 경우 만약 특정 시점에 Input 컴포넌트에 focus 되어 커서가 위치하는 방법을 알아봅니다.

webisfree.com


2년 전 교육원에서 풀스텍으로 공부 할 때 바닐라 JavaScript에 focus 이벤트를 사용했던 기억이 나서

React에서는 어떻게 사용 해야 하는 지 알아보고 정리 해보았다.

 

구현 과정

1. 비밀번호 기능을 만든다.

import React from "react";

const Test = () => {
  return (
    <div style={{ marginLeft: "100px", marginTop: "100px" }}>
      <input type="password" placeholder="비밀번호" />
      <br />
      <input type="password" placeholder="비밀번호 확인" />
    </div>
  );
};

export default Test;

 

2. focus 이벤트를 사용하고자 하는 input 태그에 ref 속성을 넣어준다.

import React, { useRef } from "react";

const Test = () => {
  const focusRef = useRef();

  return (
    <div style={{ marginLeft: "100px", marginTop: "100px" }}>
      <input type="password" placeholder="비밀번호" ref={focusRef} />
      <br />
      <input type="password" placeholder="비밀번호 확인" />
    </div>
  );
};

export default Test;

 

3. focus 이벤트를 사용한다.

비밀번호 기능에 focus 이벤트를 사용하는 경우이기 때문에 비밀번호가 서로 일치하지 않은 경우

비밀번호와 비밀번호 확인의 value를 ""로 변경하고 비밀번호에 focus 되도록 구현했다.

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

const Test = () => {
  const focusRef = useRef();
  const [userInfo, setUserInfo] = useState({
    password: "",
    passwordCheck: "",
  });

  const inputHandler = (e) => {
    setUserInfo({ ...userInfo, [e.target.name]: e.target.value });
  };

  const login = () => {
    if (userInfo.password !== userInfo.passwordCheck) {
      setUserInfo({ ...userInfo, password: "", passwordCheck: "" });
      focusRef.current.focus();
      return;
    }

    alert("로그인 성공");
  };

  return (
    <div style={{ marginLeft: "100px", marginTop: "100px" }}>
      <input
        type="password"
        placeholder="비밀번호"
        ref={focusRef}
        name="password"
        onChange={(e) => {
          inputHandler(e);
        }}
        value={userInfo.password}
      />
      <br />
      <input
        type="password"
        placeholder="비밀번호 확인"
        name="passwordCheck"
        onChange={(e) => {
          inputHandler(e);
        }}
        value={userInfo.passwordCheck}
      />
      <button onClick={login}>로그인</button>
    </div>
  );
};

export default Test;

728x90