Skip to content

Instantly share code, notes, and snippets.

@chirag-chhajed
Last active September 24, 2023 13:58
Show Gist options
  • Save chirag-chhajed/4d973214b86617ebde023ab518ff3c2c to your computer and use it in GitHub Desktop.
Save chirag-chhajed/4d973214b86617ebde023ab518ff3c2c to your computer and use it in GitHub Desktop.
import React,{useState} from "react"
export default function Form() {
const [formData, setFormData] = useState({
email: "",
password: "",
passwordConfirm: "",
joinedNewsletter: true
})
function handleChange(event) {
const {name, value, type, checked} = event.target
setFormData(prevFormData => ({
...prevFormData,
[name]: type === "checkbox" ? checked : value
}))
}
function handleSubmit(event) {
event.preventDefault()
if(formData.password === formData.passwordConfirm) {
console.log("Successfully signed up")
} else {
console.log("Passwords do not match")
return
}
if(formData.joinedNewsletter) {
console.log("Thanks for signing up for our newsletter!")
}
}
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="password"
onChange={handleChange}
value={formData.password}
/>
<input
type="password"
placeholder="Confirm password"
className="form--input"
name="passwordConfirm"
onChange={handleChange}
value={formData.passwordConfirm}
/>
<div className="form--marketing">
<input
id="okayToEmail"
type="checkbox"
name="joinedNewsletter"
onChange={handleChange}
checked={formData.joinedNewsletter}
/>
<label htmlFor="okayToEmail">I want to join the newsletter</label>
</div>
<button>
Sign up
</button>
</form>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment