input 포커스 이동 (useRef)

박서현·2023년 8월 29일
post-thumbnail
  • id 입력값이 5보다 크거나 같으면 비밀번호 입력창으로 포커스 이동
import React, { useEffect, useRef, useState } from 'react'

function App() {

  const idRef = useRef('')
  const pwRef = useRef('')

  const [id, setId] = useState('')

  //화면이 렌더링 될 때, 어떤 작업을 하고 싶다 : useEffect
  useEffect(() => {
    //input 태그를 지칭한것
    idRef.current.focus();
  }, [])

  useEffect(() => {
    if (id.length >= 5) {
      pwRef.current.focus();
    }
  }, [id]) //id값이 바뀔 때 마다 동작


  return (
    <>
      <div>
        아이디 :
        <input
          value={id}
          onChange={(event) => {
            setId(event.target.value)
          }}
          type='text'
          ref={idRef} />
      </div>
      <div>
        비밀번호   : <input type='password' ref={pwRef}/>
      </div>
    </>
  )
}

export default App

0개의 댓글