
Setting Default Value in a React Input Field with Validation
Last updated 2 weeks, 3 days ago | 35 views 75 5

First page link: How to Set the Default Value of a Text Input Field Using JavaScript
Great! Here's a React version of setting the default value of a text input field, complete with explanation, validation, and form control — the modern way to manage forms in React.
⚛️ Setting Default Value in a React Input Field with Validation
In React, input fields are usually controlled components, meaning their values are tied to component state. This makes it easy to set, update, and validate input values dynamically.
In this article, you'll learn:
-
How to set default values in React forms
-
How to prevent submission if fields are empty
-
A complete working React form example
Controlled vs Uncontrolled Inputs
-
Controlled Input: Value is controlled by React state via
useState
-
Uncontrolled Input: Uses a
ref
to access the DOM node directly
In most modern apps, controlled inputs are preferred.
✅ React Example: Default Value + Validation
import React, { useState } from "react";
function UserForm() {
const [username, setUsername] = useState("default_user"); // default value
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (!username.trim() || !password.trim()) {
setError("Username and Password cannot be empty.");
return;
}
setError("");
console.log("Form submitted:", { username, password });
// Optionally reset form
setUsername("default_user");
setPassword("");
};
return (
<div style={{ maxWidth: "400px", margin: "40px auto" }}>
<h2>React Form</h2>
<form onSubmit={handleSubmit}>
<label>Username:</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
style={{ width: "100%", padding: "8px", marginBottom: "10px" }}
/>
<label>Password:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
style={{ width: "100%", padding: "8px", marginBottom: "10px" }}
/>
{error && <p style={{ color: "red" }}>{error}</p>}
<button type="submit" style={{ padding: "10px 20px" }}>
Submit
</button>
</form>
</div>
);
}
export default UserForm;
Breakdown
-
useState("default_user")
: Sets the default username -
value={username}
: Binds the input value to state -
onChange={(e) => setUsername(e.target.value)}
: Updates the value as the user types -
handleSubmit
: Validates the input values before submission
Tips
-
Use
trim()
to avoid spaces-only input -
Place default values in state initialization
-
You can preload dynamic default values using
useEffect()
if loading from an API
useEffect(() => {
fetchUser().then(data => setUsername(data.username));
}, []);
⚠️ Common Pitfalls
Pitfall | Solution |
---|---|
Input doesn’t update when typing | Make sure value and onChange are properly set |
Default doesn’t appear | Ensure initial state has the desired default |
Form submits with blanks | Add .trim() check and preventDefault() in handler |
✅ Summary
-
React uses controlled components to manage form inputs.
-
You can set default values using
useState("value")
. -
Validate fields before submission to improve UX and security.