본문 바로가기
Research/React

React handling multiple inputs data with useState

by RIEM 2023. 10. 24.
import { useState } from 'react';

const EventPractice = () => {
  const [username, setUsername] = useState('');
  const [message, setMessage] = useState('');

  const onChangeUsername = (e) => setUsername(e.target.value);
  const onChangeMessage = (e) => setMessage(e.target.value);

  const onClick = () => {
    alert(`${username} : ${message}`);
    setUsername('');
    setMessage('');
  };

  const onKeyPress = (e) => {
    if (e.key === 'Enter') {
      onClick();
    }
  };

  return (
    <div>
      <h1>Event Practice :D</h1>
      <input
        type="text"
        name="username"
        placeholder="사용자명"
        value={username}
        onChange={onChangeUsername}
      />

      <input
        type="text"
        name="message"
        placeholder="여기에 입력"
        value={message}
        onChange={onChangeMessage}
        onKeyPress={onKeyPress}
      />
      <button onClick={onClick}>Confirm</button>
    </div>
  );
};
export default EventPractice;

input과 button의 event 실행 함수를 {} 안에 직접 코드를 넣기보다 메서드 형태로 넣는 것이 더 가독성이 좋다.

 

input을 여러개 다룰 경우

event 객체를 활용 e.target.name으로 이벤트 이름을 추적해서 제어한다.

import { useState } from 'react';

const EventPractice = () => {
  const [form, setForm] = useState({
    username: '',
    message: '',
  });

  const { username, message } = form;

  const onChange = (e) => {
    const nextForm = {
      ...form, // 기존 form 객체 복사
      [e.target.name]: e.target.value, // 덮어씌우기
    };
    setForm(nextForm);
  };

  const onClick = () => {
    alert(`${username} : ${message}`);
    setForm({
      username: '',
      message: '',
    });
  };

  const onKeyPress = (e) => {
    if (e.key === 'Enter') {
      onClick();
    }
  };

  return (
    <div>
      <h1>Event Practice :D</h1>
      <input
        type="text"
        name="username"
        placeholder="사용자명"
        value={username}
        onChange={onChange}
      />

      <input
        type="text"
        name="message"
        placeholder="여기에 입력"
        value={message}
        onChange={onChange}
        onKeyPress={onKeyPress}
      />
      <button onClick={onClick}>Confirm</button>
    </div>
  );
};
export default EventPractice;

We put onChange method into every input elements. onClick contains `setForm` method which can track the name of input from e.target.name so that it update only the input triggered.

I made some changes for current project Franklin-note. 

import { useState } from 'react';

const EventPractice = () => {
  const [form, setForm] = useState({
    sentence: '',
    url: '',
  });

  const { sentence, url } = form;

  const onChange = (e) => {
    const nextForm = {
      ...form,
      [e.target.name]: e.target.value,
    };
    setForm(nextForm);
  };

  const onClick = () => {
    alert(`"${sentence}", from ${url}`);
    setForm({
      sentence: '',
      url: '',
    });
  };

  const onKeyPress = (e) => {
    if (e.key === 'Enter') onClick();
  };

  return (
    <div>
      <h1>Let us Collect</h1>
      <input
        type="text"
        name="sentence"
        placeholder="write your sentence"
        value={sentence}
        onChange={onChange}
      />
      <input
        type="text"
        name="url"
        placeholder="url here.."
        value={url}
        onChange={onChange}
        onKeyPress={onKeyPress}
      />
      <button onClick={onClick}>Confirm</button>
    </div>
  );
};

export default EventPractice;

댓글