React Forms
React Forms
Forms are an integral part of any modern web application. It allows the users
to interact with the application as well as gather information from the users.
Forms can perform many tasks that depend on the nature of your business
requirements and logic such as authentication of the user, adding user,
searching, filtering, booking, ordering, etc. A form can contain text fields,
buttons, checkbox, radio button, etc.
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. You
can control changes by adding event handlers in the onChange attribute and
that event handler will be used to update the state of the variable.
function MyForm() {
return (
<form>
</label>
</form>
Handling Forms
Handling forms is about how you handle the data when it changes value or
gets submitted.
When the data is handled by the components, all the data is stored in the
component state.
You can control changes by adding event handlers in the onChange attribute.
function MyForm() {
return (
<form>
<input
type="text"
value={name}
/>
</label>
</form>
Submitting Forms
You can control the submit action by adding an event handler in
the onSubmit attribute for the <form>:
function MyForm() {
event.preventDefault();
}
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
/>
</label>
</form>
Textarea
The textarea element in React is slightly different from ordinary HTML.
function MyForm() {
);
setTextarea(event.target.value)
}
return (
<form>
</form>
Select
A drop down list, or a select box, in React is also a bit different from HTML.
function MyForm() {
setMyCar(event.target.value)
return (
<form>
<option value="Ford">Ford</option>
<option value="Volvo">Volvo</option>
<option value="Fiat">Fiat</option>
</select>
</form>
}
Radio Button
Program:- Create a React Form for select any of pizza size using radio button.
<input
type='radio'
name='topping'
value='Medium'
checked={topping === 'Medium'}
onChange={onOptionChange}
/>
<label>Medium</label>
<input
type='radio'
name='topping'
value='Large'
checked={topping === 'Large'}
onChange={onOptionChange}
/>
<label>Large</label>
</form>
<p>
Select topping <strong>{topping}</strong>
</p>
</div>
);
}
export default Myform
if(!regexEmail.test(email))
{ alert("enter valid email address");}
if(!regexPass.test(pass))
{ alert("Password must have 8 characters which contain only
characters, numeric digits, underscore and first
character must be a letter");
}
setEmail("");
setPass("");
} );
return (
<form onSubmit={handleSubmit}>
<label>E-Mail:
<input type="email" value={email} onChange={handleEmailchange}/>
</label> <br/>
<label>Password:
<input type="password"value={pass} onChange={handlePasswordchange}/>
</label> <br/>
<button type="submit">submit</button>
</form>
)
}