[React] useRef를 통한 focus 기능

·2023년 8월 23일
0

✏️구현 코드

  • 입력값 조건 추가
  • 조건에 맞지 않은경우, 해당 입력칸으로 focus

DiaryEditor.js

import { useRef, useState } from "react";

const DiaryEditor = () => {
    const authorInput = useRef();
    const contentInput = useRef();

    const [state, setState] = useState({
        author: "",
        content: "",
        emotion: 1
    })
    const handleChangeState = (e) => {
        setState({
            ...state,
            [e.target.name]: e.target.value
        })
    }

    const handleSubmit = () => {
        console.log(state);
      	
      	// author input 조건이 충족되지 않은 경우
        if (state.author.length < 1) {
            alert("작성자는 최소 1글자 이상 입력해주세요");
            authorInput.current.focus();
            return;
        }
      
      	// content input 조건이 충족되지 않은 경우
        if (state.content.length < 5) {
            alert("일기 본문은 최소 5글자 이상 입력해주세요");
            contentInput.current.focus();
            return;
        }
        alert("저장 성공!")
    }

➰결과

0개의 댓글