ContactForm
ContactForm.tsx
import React, { useState } from 'react';
import './ContactForm.css';
type ContactFormProps = {
onSubmit: (contact: ContactFormData) => void;
};
type ContactFormData = {
contact: string;
firstName: string;
lastName: string;
companyEmail: string;
receivePromotions: boolean;
};
const initialFormData: ContactFormData = {
contact: '',
firstName: '',
lastName: '',
companyEmail: '',
receivePromotions: false,
};
const ContactForm = (props: ContactFormProps) => {
const { onSubmit } = props;
const [formData, setFormData] = useState<ContactFormData>(initialFormData);
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
onSubmit(formData);
setFormData(initialFormData);
};
const handleChange = (event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const { name, value, type, checked } = event.target;
setFormData(prevFormData => ({
...prevFormData,
[name]: type === 'checkbox' ? checked : value
}));
};
return (
<form className="contact-form-container" onSubmit={handleSubmit}>
<h2>Contact Form</h2>
<div className="form-group">
<label htmlFor="contact">Contact:</label>
<input
type="text"
id="contact"
name="contact"
value={formData.contact}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="firstName">First Name:</label>
<input
type="text"
id="firstName"
name="firstName"
value={formData.firstName}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="lastName">Last Name:</label>
<input
type="text"
id="lastName"
name="lastName"
value={formData.lastName}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="companyEmail">Company Email:</label>
<input
type="email"
id="companyEmail"
name="companyEmail"
value={formData.companyEmail}
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="receivePromotions">Receive Promotions:</label>
<select
id="receivePromotions"
name="receivePromotions"
value={formData.receivePromotions.toString()}
onChange={handleChange}
required
>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default ContactForm;
ContactForm.module.css
.contact-form-container {
display: flex;
flex-direction: column;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
max-width: 600px;
margin: 0 auto;
}
.form-group {
display: flex;
flex-direction: column;
margin-bottom: 10px;
}
label {
font-weight: bold;
margin-bottom: 5px;
}
input[type='text'],
input[type='email'],
select {
padding: 10px;
border: 1px solid