8 May 2024
import React, { useState } from 'react';
const RegistrationForm = () => {
const [formData, setFormData] = useState({
username: '',
email: '',
password: ''
});
// Handle input change
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};
// Handle form submission
const handleSubmit = (e) => {
e.preventDefault();
// Process form data here
console.log('Form submitted:', formData);
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</label>
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
</label>
<button type="submit">Register</button>
</form>
);
};
export default RegistrationForm;
value
attribute and updates the state via the onChange
event handler.handleChange
function updates the corresponding state variable when the user types in the input fields.handleSubmit
function prevents the default form submission behavior and processes the form data, which is logged to the console in this example.Uncontrolled components rely on the DOM to keep track of form data. This approach can be useful for simple forms or when integrating with non-React libraries.
import React, { useRef } from 'react';
const UncontrolledForm = () => {
const usernameRef = useRef();
const emailRef = useRef();
const passwordRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
console.log('Username:', usernameRef.current.value);
console.log('Email:', emailRef.current.value);
console.log('Password:', passwordRef.current.value);
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input type="text" ref={usernameRef} />
</label>
<label>
Email:
<input type="email" ref={emailRef} />
</label>
<label>
Password:
<input type="password" ref={passwordRef} />
</label>
<button type="submit">Submit</button>
</form>
);
};
export default UncontrolledForm;
In this example, refs are used to directly access the input values upon form submission.
handleSubmit
function.const handleSubmit = (e) => {
e.preventDefault();
if (formData.username === '' || formData.email === '' || formData.password === '') {
alert('All fields are required');
return;
}
// Process form data here
console.log('Form submitted:', formData);
};
handleChange
function.const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
if (name === 'email' && !value.includes('@')) {
console.log('Please enter a valid email address');
}
};
useState
hook is the recommended approach as it provides better control over form data and simplifies validation. Uncontrolled components can be used for simpler forms or when integrating with other libraries. By mastering these techniques, you can build dynamic and interactive forms in your React applications.