<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 이벤트 만들어서 form
의 onSubmit
에 달아주면 된다.
React.FormEvent<HTMLFormElement>
이벤트 타입 지정 필수event.preventDefault()
는 submit이 자동적으로 제출해 새로고침 이벤트를 막아줌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;
input
기본 디자인을 display : none;
을 통해 안보이게 만든다.input
위에 button
을 하나 생성button
에 useRef
를 통해 input
의 트리거 역할을 하도록 만듦.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