form elements in react js code example
Example 1: form in react
import React, { useState } from "react";
import "./styles.css";
function Form() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<form>
<input
value={firstName}
onChange={e => setFirstName(e.target.value)}
placeholder="First name"
type="text"
name="firstName"
required
/>
<input
value={lastName}
onChange={e => setLastName(e.target.value)}
placeholder="Last name"
type="text"
name="lastName"
required
/>
<input
value={email}
onChange={e => setEmail(e.target.value)}
placeholder="Email address"
type="email"
name="email"
required
/>
<input
value={password}
onChange={e => setPassword(e.target.value)}
placeholder="Password"
type="password"
name="password"
required
/>
<button type="submit">Submit</button>
</form>
);
}
export default Form;
Example 2: form in react js
import React, { useState } from "react";
export function Form() {
const [name, setName] = useState("");
const handleSubmit = (evt) => {
evt.preventDefault();
alert(`Submitting Name ${name}`)
}
const changeName = (e) => {
setName(e.target.value)
}
return (
<form onSubmit={handleSubmit}>
<br />
<br />
<label>
Frirst Name:
<input
type="text"
value={name}
onChange={changeName}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
export default Form;