Handling input forms with useState
in React involves creating state variables to store the values of input fields and updating them as the user interacts with the form.
Handling input forms with useState:
- State Variables: Define state variables to hold the values of input fields. Each input field typically has its own state variable.
- Binding Input Values: Bind the value of each input field to its corresponding state variable. This ensures that the input field displays the current value stored in the state.
-
Event Handlers: Create event handler functions to update the state variables as the user enters or modifies input. These functions typically listen for events like
onChange
for text inputs oronClick
for buttons. -
Updating State: When the user interacts with the input fields, the event handlers update the state variables using
setState
, triggering a re-render to reflect the changes in the UI. - Submitting the Form: When the user submits the form, you can access the values stored in the state variables to perform further actions, such as validation or sending data to a server.
Example: Below is an example of handling input forms with useState.
Javascript
import React, { useState
} from 'react' ;
import './App.css' ;
const FormExample = () => { const [name, setName] = useState( '' );
const [email, setEmail] = useState( '' );
// Event handlers to update state variables
const handleNameChange = (event) => {
setName(event.target.value);
};
const handleEmailChange = (event) => {
setEmail(event.target.value);
};
const handleSubmit = (event) => {
// Prevent default form submission
event.preventDefault();
console.log( 'Name:' , name);
console.log( 'Email:' , email);
};
return (
<div className= "form-container" >
<h2>Input Form</h2>
<form onSubmit={handleSubmit}>
<div className= "form-group" >
<label>Name:</label>
<input
type= "text"
value={name}
onChange={handleNameChange}
/>
</div>
<div className= "form-group" >
<label>Email:</label>
<input
type= "email"
value={email}
onChange={handleEmailChange}
/>
</div>
<button type= "submit" >Submit</button>
</form>
</div>
);
}; export default FormExample;
|
CSS
.form-container { max-width : 400px ;
margin : auto ;
padding : 20px ;
border : 1px solid #ccc ;
border-radius: 5px ;
} .form-group { margin-bottom : 15px ;
} label { display : block ;
margin-bottom : 5px ;
} input[type= "text" ],
input[type= "email" ] {
width : 100% ;
padding : 8px ;
font-size : 16px ;
border : 1px solid #ccc ;
border-radius: 5px ;
} button { padding : 10px 20px ;
font-size : 16px ;
background-color : #007bff ;
color : #fff ;
border : none ;
border-radius: 5px ;
cursor : pointer ;
} button:hover { background-color : #0056b3 ;
} |
Output: