react input 상태 관리

Doum Kim·2020년 5월 11일
3

React - 기초

목록 보기
9/20

input 상태 관리하기

하나의 input 상태 관리

InputSample.jsx

import React from "react";

const InputSample = () => {
  return (
    <>
      <h1>TEXT</h1>
      <input type="text" placeholder="입력하세요" />
      <button>Reset</button>
    </>
  );
};

export default InputSample;

input에 입력하는 값을 inputText state로 관리하고 reset 버튼을 누르면 inputText를 초기화 시켜준다. input 입력 값은 onChange 이벤트 객체에서 target.value로 가져온다.
reset을 위해 input의 value값을 inputText로 해준다.

import React, { useState } from "react";

const InputSample = () => {
  const [inputText, setInputText] = useState("");
  const onChangeInput = e => {
    setInputText(e.target.value);
  };
  const onReset = () => {
    setInputText("");
  };

  return (
    <>
      <h1>Text: {inputText}</h1>
      <input
        type="text"
        value={inputText}
        placeholder="입력하세요"
        onChange={onChangeInput}
      />
      <button onClick={onReset}>Reset</button>
    </>
  );
};

export default InputSample;

여러 개의 input 상태 관리

여러개의 input의 상태를 관리할 때는 여러개의 state를 만들어서 구분하기보다는 input의 name을 설정해서 관리해준다.

InputSample.jsx

import React, { useState } from "react";

const InputSample = () => {
  const [user, setUser] = useState({
    username: "",
    age: ""
  });
  const { username, age } = user; //user 객체 비구조화 할당

  const onChangeInput = e => {
    const { name, value } = e.target;
    setUser({ ...user, [name]: value }); //...user로 불변성 유지와  [name]을 사용해서 현재 입력하고 있는 input의 name의 상태 변경.
  };

  const onReset = () => {
    setUser({ username: "", age: "" });
  };

  return (
    <>
      <h1>
        이름: {username}, 나이: {age}
      </h1>
      <input
        type="text"
        name="username"
        value={username}
        placeholder="이름"
        onChange={onChangeInput}
      />
      <input
        type="number"
        name="age"
        value={age}
        placeholder="나이"
        onChange={onChangeInput}
      />
      <button onClick={onReset}>Reset</button>
    </>
  );
};

export default InputSample;

useRef 이용해 focus 주기

useRef를 사용해서 특정 DOM에 접근이 가능하다. 이러한 특징을 이용해서 reset버튼을 눌렀을 때 특정 name input에 focus를 줄 수 있다.

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

const InputSample = () => {
  const inputRef = useRef(); //ref 객체 생성.
  
  const [user, setUser] = useState({
    username: "",
    age: ""
  });
  const { username, age } = user;

  const onChangeInput = e => {
    const { name, value } = e.target;
    setUser({ ...user, [name]: value });
  };

  const onReset = () => {
    setUser({ username: "", age: "" });
    inputRef.current.focus();
  };

  return (
    <>
      <h1>
        이름: {username}, 나이: {age}
      </h1>
      <input
        type="text"
        name="username"
        value={username}
        placeholder="이름"
        onChange={onChangeInput}
        ref={inputRef} // 접근할 DOM에 ref 값 설정
      />
      <input
        type="number"
        name="age"
        value={age}
        placeholder="나이"
        onChange={onChangeInput}
      />
      <button onClick={onReset}>Reset</button>
    </>
  );
};

export default InputSample;

0개의 댓글