1. Controlled Component: Imagine you’re building a form to let users register for an account on your website. You want to provide real-time validation feedback as they fill out their details.
Here’s how you might use a controlled component to accomplish this:
import React, { useState } from 'react';
function RegistrationForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
const handlePasswordChange = (event) => {
setPassword(event.target.value);
};
const handleSubmit = (event) => {
alert('A form was submitted: ' + username + " " + password);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input type="text" value={username} onChange={handleUsernameChange} />
</label>
<label>
Password:
<input type="password" value={password} onChange={handlePasswordChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
export default RegistrationForm;
2. Uncontrolled Component: Suppose you’re building a simple search bar for your website that doesn’t need to provide real-time feedback.
Here’s how you might use an uncontrolled component for this:
import React, { useRef } from 'react';
function SearchBar() {
const input = useRef();
const handleSubmit = (event) => {
alert('Search term: ' + input.current.value);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<input type="text" ref={input} placeholder="Search..." />
<input type="submit" value="Search" />
</form>
);
}
export default SearchBar;