리액트 회고록 4. form 태그로 input 관리하기.

양희준·2022년 6월 25일
0

form 태그의 사용의 중요성

form 태그를 사용하면 코드가 간결해지는 현상을 경험하였다. 코드가 짧아지고 가독성도 증가하여 HTML 태그의 사용법도 아는것이 중요하다라고 느낀 계기가 되었다.

input 태그만 사용하여 입력폼 만들기

일반적으로 ID와 PW만 사용해서 input의 입력을 받고 button으로 ID와 PW를 출력한 뒤 input을 초기화 하는 기본 로직이다.

import React, { useRef } from "react";

function App() {
  const idRef = useRef(null);
  const pwRef = useRef(null);

  // ref를 이용해서 버튼을 클릭하면 ref의 value를 출력한다.
  const hanldeOnClick = () => {
    console.log(idRef.current.value, pwRef.current.value);
    // input 초기화
    idRef.current.value = null;
    pwRef.current.value = null;
  };

  return (
    <div>
      <input ref={idRef} type="text" placeholder="id" />
      <input ref={pwRef} type="password" placeholder="pw" />
      <button onClick={hanldeOnClick}>제출하기</button>
    </div>
  );
}

export default App;

비밀번호를 입력한 뒤에 Enter를 입력하면 아이디와 비밀번호를 출력한 뒤 초기화 하는 로직을 추가하는 코드이다.

import React, { useRef } from "react";

function App() {
  const idRef = useRef(null);
  const pwRef = useRef(null);

  const hanldeOnClick = () => {
    console.log(idRef.current.value, pwRef.current.value);
    idRef.current.value = null;
    pwRef.current.value = null;
  };
  // "Enter"를 누르면 출력하고 input의 value를 초기화 하는 함수 생성
  const hanldeOnKeyDown = (e) => {
    if (e.key !== "Enter") return;
    console.log(idRef.current.value, pwRef.current.value);
    idRef.current.value = null;
    pwRef.current.value = null;
  };

  return (
    <div>
      <input ref={idRef} type="text" placeholder="id" />
      <input
        ref={pwRef}
        onKeyDown={hanldeOnKeyDown}
        type="password"
        placeholder="pw"
      />
      <button onClick={hanldeOnClick}>제출하기</button>
    </div>
  );
}

export default App;

이렇게 사용하면 함수 2개와 Ref 2개 변수를 사용한다. 하지만 form을 이용하면 코드를 더욱더 가독성 좋게 만들수 있다.

form 태그를 사용하여 입력폼 만들기

form 태그를 사용할 때는 preventDefault() 메소드를 호출해야 한다. preventDefault 메소드는 기본 이벤트를 막는 효과를 가지고 있다. form의 용도는 전송이므로 새로고침이 일어나게 된다. 새로고침을 막기 위해서 사용한다.

import React from "react";

function App() {
  const hadleOnSubmit = (e) => {
    e.preventDefault();
    // form의 input의 설정된 name의 값을 가져온다.
    console.log(e.target.id.value, e.target.pw.value);
    // 입력 요소 reset
    e.target.reset();
  };

  return (
    <form onSubmit={hadleOnSubmit}>
      <input name="id" type="text" placeholder="id" />
      <input name="pw" type="password" placeholder="pw" />
      <button type="submit">제출하기</button>
    </form>
  );
}

export default App;

form 태그는 Enter를 입력해도 form에 있는 정보를 전송한다. 그 점을 이용해서 예외처리를 하면 onKeyDown 이벤트를 사용하지 않아도 되며 구조분해할당을 이용하면 코드를 더욱더 간결하게 만들 수 있다.

import React from "react";

function App() {
  const hadleOnSubmit = (e) => {
    e.preventDefault();
    // 구조 분해 할당을 이용해서 이름을 줄일 수 있다.
    const { id, pw } = e.target;
    // `Enter` 예외처리
    if (id.value.length === 0) return alert("ID Check Plz");
    console.log(id.value, pw.value);
    e.target.reset();
  };

  return (
    <form onSubmit={hadleOnSubmit}>
      <input name="id" type="text" placeholder="id" />
      <input name="pw" type="password" placeholder="pw" />
      <button type="submit">제출하기</button>
    </form>
  );
}

export default App;

HTML의 태그의 특성을 이용하면 코드가 더욱더 간결해지는 경험을 하였다. HTML이라고 소홀히 하지 않고 공부해서 더욱더 좋은 코드를 고민할 수 있는 방향성을 얻어서 좋은 시간이였다.

profile
JS 코린이

0개의 댓글