지금까지 배운걸로 sign up form 연습을 했다.
아래의 코드를 살펴보자
import React from "react";
export default function App() {
const [formData, setFormData] = React.useState({
email: "",
pw: "",
confirmPw: "",
okayToEmail: true,
});
function handleChange(event) {
const { name, value, type, checked } = event.target;
setFormData((prevFormData) => {
return {
...prevFormData,
[name]: type === "checkbox" ? checked : value,
};
});
}
function handleSubmit(event) {
event.preventDefault();
if (formData.pw === formData.confirmPw) {
console.log("Successfully signed up");
} else {
console.log("Password do not match");
}
}
return (
<div className="form-container">
<form className="form" onSubmit={handleSubmit}>
<input
type="email"
placeholder="Email address"
className="form--input"
name="email"
onChange={handleChange}
value={formData.email}
/>
<input
type="password"
placeholder="Password"
className="form--input"
name="pw"
onChange={handleChange}
value={formData.pw}
/>
<input
type="password"
placeholder="Confirm password"
className="form--input"
name="confirmPw"
onChange={handleChange}
value={formData.confirmPw}
/>
<div className="form--marketing">
<input
id="okayToEmail"
type="checkbox"
name="okayToEmail"
onChange={handleChange}
checked={formData.okayToEmail}
/>
<label htmlFor="okayToEmail">I want to join the newsletter</label>
</div>
<button className="form--submit">Sign up</button>
</form>
</div>
);
}
이 부분에는 자바스크립트로 패스워드가 같은지
같으면 이걸 log해주고 아니면 다른걸 log하라고 구현.
그리고 패스워드 다를때 다음으로 안넘어가도록
return을 넣어줌.
function handleSubmit(event) {
event.preventDefault();
if (formData.pw === formData.confirmPw) {
console.log("Successfully signed up");
} else {
console.log("Password do not match");
}
}