[React.js] DOM조작하기 - useRef

n-u·2022년 6월 20일
0

TIL

목록 보기
17/24
post-thumbnail

DOM조작하기 - useRef

버튼을 클릭했을 때, 작성자와 일기가 정상적으로 입력되었는지 확인하고 아니라면 focus하기

useRef

DOM요소를 선택 조작을 도와주는 기능을 가지고 있다.

1. 설정

import {useRef,useState} from "react";
  • react를 import할때, useRef를 추가하여 import한다.

2. 변수에 useRef()를 지정

	const authorInput = useRef();
    const contentInput = useRef();

반환값을 상수에 담아 사용한다.

  • 이때 상수에는 React.MutableRefObject(Html에 접근하도록 한다.)가 저장된다.

3. DOM요소에 바인딩 시켜주기

		<div>
            <input 
            ref = {authorInput}
            name = "author"
            value = {state.author}
            onChange = {handleChange}
            />
        </div>

ref = {authorInput}을 작성해준다.

  • authorInput으로 input요소에 접근할 수 있게 되었다.

4. useRef의 값을 이용해 DOM요소 제어하기

const handleSubmit = ()=>{
        if(state.author.length <1){
            authorInput.current.focus();
            //useRef는 current메서드를 이용해 사용할 수 있다.
            return;
        }

        if(state.content.length < 5){
            contentInput.current.focus();
            return;
        }
        alert("저장 성공!");
    }
  • useRef를 이용한 상수는 현재가리키는 값을 current프로퍼티로 불러올 수 있다.

최종 코드

입력된 값의 legnt에 조건이 맞지 않을 경우 focus기능을 이용하도록 useRef를 이용하였다.

import {useRef,useState} from "react";

const DiaryEditor = ()=>{

    const authorInput = useRef();
    const contentInput = useRef();

    const [state , setState] = useState({
        author : "",
        content : "",
        emotion : "1",
    });


    const handleChange = (e)=>{
        setState({
            ...state,
            [e.target.name]  : e.target.value,
        })
    }

    const handleSubmit = ()=>{
        if(state.author.length <1){
            //focus
            authorInput.current.focus();
            //useRef는 current메서드를 이용해 사용할 수 있다.
            return;
        }

        if(state.content.length < 5){
            contentInput.current.focus();
            return;
        }
        alert("저장 성공!");
    }

    return(
    <div className="DiaryEditor">
        <h2>오늘의 일기</h2>
        <div>
            <input 
            ref = {authorInput}
            name = "author"
            value = {state.author}
            onChange = {handleChange}
            />
        </div>
        <div>
            <textarea 
            ref = {contentInput}
            name = "content"
            value = {state.content}
            onChange = {handleChange}/>

        </div>
        <div>
            <span>오늘의 감정점수 : </span>
            <select 
            name = "emotion"
            value = {state.emotion}
            onChange = {handleChange}
            >
                <option vlaue ={1}>1</option>
                <option vlaue ={2}>2</option>
                <option vlaue ={3}>3</option>
                <option vlaue ={4}>4</option>
                <option vlaue ={5}>5</option>
            </select>
        </div>
        <div>
            <button onClick={handleSubmit}>일기 저장하기</button>
        </div>
    </div>
    )
}
export default DiaryEditor;
profile
기록하며 발전하는 삶

0개의 댓글