React Form 관리하기 (+ file input)

bicco2·2022년 12월 2일
0

React Form 관리

<form onSubmit={onSubmit}>
		<span>input1</span>
    <input id="input1" />

    <span>input2</span>
    <input id="input2" />
</form>

이런식으로 form 구성하고

function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
  event.preventDefault()
	console.log(e.currentTarget."id".value);
}

submit 이벤트 만들어서 formonSubmit에 달아주면 된다.

  • Typescript의 경우 React.FormEvent<HTMLFormElement> 이벤트 타입 지정 필수
  • event.preventDefault()는 submit이 자동적으로 제출해 새로고침 이벤트를 막아줌






Input에서 파일 업로드 관리

import test from "../../../assets/test.png";

const ImgInputComponent = () => {
  const hiddenFileInput = React.useRef<HTMLInputElement>(null);

  const handleClick = () => {
    hiddenFileInput.current!.click();
  };

  const handleChange = (e: any) => {
    const fileUploaded = e.target.files[0];
    console.log(fileUploaded);
  };
return (
      <button type="button" onClick={handleClick}>
        <img src={test} />
      </button>
      <input
        type="file"
        id="eventImgs"
        ref={hiddenFileInput}
        onChange={handleChange}
      ></input>
  );
};

export default ImgInputComponent;
  1. input 기본 디자인을 display : none; 을 통해 안보이게 만든다.
  2. input 위에 button 을 하나 생성
  3. buttonuseRef를 통해 input의 트리거 역할을 하도록 만듦.
  4. 기본 Input type=”file”에 등록하는 이벤트 생성 후 그대로 진행



예시


참고

https://epicreact.dev/how-to-type-a-react-form-on-submit-handler/
https://medium.com/web-dev-survey-from-kyoto/how-to-customize-the-file-upload-button-in-react-b3866a5973d8

profile
FE 개발자다?

0개의 댓글