In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state.
React Frontend Framework
React Tutorial
Advertisement
Google AdSense Slot (LEADERBOARD)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
User Inputs
8 min read
•
Chapter 14 of 26
React Forms
Handle forms with React controlled components, manage multiple input fields with a single handler, and handle form submit.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
<div id="root"></div>
<script type="text/babel">
function FormExample() {
const [name, setName] = React.useState("");
const handleSubmit = (e) => {
e.preventDefault();
alert(`Form submitted for: ${name}`);
};
return (
<form onSubmit={handleSubmit} style={{maxWidth: "300px"}}>
<label style={{display: "block", marginBottom: "6px", fontWeight: "bold"}}>Enter Employee Name:</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
style={{padding: "8px", width: "100%", boxSizing: "border-box", marginBottom: "10px", borderRadius: "6px", border: "1px solid #cbd5e1"}}
/>
<button type="submit" style={{background: "#04aa6d", color: "white", padding: "8px 16px", border: "none", borderRadius: "6px", cursor: "pointer"}}>Submit</button>
</form>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<FormExample />);
</script>
</body>
</html>
Try it Yourself >>
Opens live sandboxed code editor
Advertisement
Google AdSense Slot (IN-ARTICLE)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Community Q&A & Discussion
Verified
No questions yet. Be the first to start the discussion!