0% found this document useful (0 votes)
4 views1 page

ContactForm Practical 4

The document contains a React component for a contact form that captures a user's name and email. It includes validation to ensure both fields are filled before submission, displaying an error message if not. Upon successful submission, it alerts the user with the entered information and resets the form fields.

Uploaded by

sheetaldankher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views1 page

ContactForm Practical 4

The document contains a React component for a contact form that captures a user's name and email. It includes validation to ensure both fields are filled before submission, displaying an error message if not. Upon successful submission, it alerts the user with the entered information and resets the form fields.

Uploaded by

sheetaldankher
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

import React, { useState } from 'react';

const ContactForm = () => {


const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [error, setError] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
if (!name || !email) {
setError('Both fields are required');
} else {
setError('');
alert(`Form submitted\nName: ${name}\nEmail: ${email}`);
setName('');
setEmail('');
}
};

return (
<div>
<h2>Contact Form</h2>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
/><br /><br />
<input
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/><br /><br />
{error && <p style={{ color: 'red' }}>{error}</p>}
<button type="submit">Submit</button>
</form>
</div>
);
};

export default ContactForm;

You might also like