• React

[React] Form 만들기

Suro_1123 2024. 2. 13. 21:44

React Form 

 

 

 

 

😎 목적

  1. UseState Hook으로 form을 객체 상태로 관리 
  2. input Controlled Component (제어 컴포넌트)
  3. 객체의 값을 Bracket notation (괄호 표기법)으로 접근

 

 


 

 

👶 1. 기본 뼈대

import React from 'react'

export default function AppForm() {
  const handleSubmit = (e) => {
    e.preventDefault();
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">이름 : </label>
      <input type="text" id='name' name='name'/>

      <label htmlFor="id">ID : </label>
      <input type="text" id='id' name='id'/>

      <label htmlFor="password">Password : </label>
      <input type="password" id='password' name='password'/>
      <button>Submit</button>
    </form>
  )
}

AppForm.jsx

 

 

AppForm 실행화면

 

Form에 e.preventDefault를 해준 이유는 새로고침을 방지하기 위해서이다.

자세한 링크 : https://react-ko.dev/reference/react-dom/components/input

 

 

👨‍🦲 2. useState

import React, { useState } from 'react'

export default function AppForm() {
  const [form, setForm] = useState({name: "", id: "", password: ""});
  const handleSubmit = (e) => {
    e.preventDefault();
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">이름 : </label>
      <input type="text" id='name' name='name' value={form.name}/>

      <label htmlFor="id">ID : </label>
      <input type="text" id='id' name='id' value={form.id}/>

      <label htmlFor="password">Password : </label>
      <input type="password" id='password' name='password' value={form.password}/>
      <button>Submit</button>
    </form>
  )
}

AppForm.jsx

 

 

각 input에 value를 useState에 있는 form의 상태로 쓰게 해놨다 하지만 경고가 발생한다.

AppForm console 화면

 

onChange 핸들러가 없는 Form에 value를 제공하면 read-only 필드가 된다는 경고이다.

input을 제어 컴포넌트로 하기위해 onChange 핸들러를 달아줘야한다.

 

 

💥 Controlled vs Uncontrolled

1️⃣ Controlled Component (제어 컴포넌트)

입력 값이 생길 때마다 상태를 갱신하여 최신값을 유지하는데, 데이터와 UI에서 사용자가 입력한 값이 항상 동기화 되고 있다.

🚫 제어 컴포넌트에 전달하는 value는 undefined 또는 null 이어서는 안된다. 초기값을 비워야 하는 경우 state 변수를 빈 문자열(' ')로 초기화 해야한다.

https://react-ko.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable

 

 

2️⃣ Uncontrolled Component (비제어 컴포넌트)

일반적으로 일부 로컬 state를 가진 컴포넌트를 비제어 컴포넌트라고 부른다.

예를들어 form에 Submit 버튼이 있는데 이 버튼을 클릭할때 data를 가져올 수 있다.

 

 

 

 

3. 👱‍♂️ onChange 

import React, { useState } from 'react'

export default function AppForm() {
  const [form, setForm] = useState({name: "", id: "", password: ""});
  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(form);
  }
  const handleChange = (e) => {
    const {name, value} = e.target;
    setForm({...form, [name] : value});
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">이름 : </label>
      <input type="text" 
      id='name' name='name' 
      value={form.name} 
      onChange={handleChange}/>

      <label htmlFor="id">ID : </label>
      <input 
      type="text" 
      id='id' 
      name='id' 
      value={form.id} 
      onChange={handleChange}/>

      <label htmlFor="password">Password : </label>
      <input type="password" 
      id='password' 
      name='password' 
      value={form.password} 
      onChange={handleChange}/>
      <button>Submit</button>
    </form>
  )
}

AppForm.jsx

 

  1. 각 input에 onChange 핸들러로 handleChange 함수를 넣음 
  2. 사용자가 입력중인 input과 value를 알기위해 object destructuring (디스트럭처링)을 통해 변수에 담아줌
  3. 사용자가 입력중인 input은 동적으로 변하기 때문에 객체 접근법인 Bracket notation (괄호 표기법)을 통해 name과 value를 상태관리 해주었음.
  4. 결과값을 콘솔에 찍기위해 handleSubmit 함수에 console.log(form) 추가

 


 

😊 결과

 

 

 

참고 :

https://react-ko.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable

 

<input> – React

The library for web and native user interfaces

react-ko.dev