How to Build a Form in React

A laptop with dog

per-requirements

Basic understanding of ReactJS, HTML, CSS, React-Bootstrap, and JavaScript

npm install react-bootstrap bootstrap
import 'bootstrap/dist/css/bootstrap.min.css'
<Form><Form.Group><Form.Label>Username</Form.Label><Form.Control type="text" placeholder="Enter username" /><Form.Text className="text-muted">We'll never share your details with anyone else.</Form.Text></Form.Group><Form.Group controlId="formBasicPassword"><Form.Label>Password</Form.Label><Form.Control type="password" placeholder="Password" /></Form.Group></Form>

First step :

Create a component state that controls the value of the input element. So, within the component, I am going to add state properties called username and password. And initialized it to assign to the empty string.

state = {username : "",password : ""}
<Form><Form.Group><Form.Label>Username</Form.Label><Form.Control type="text" placeholder="Enter username"  
value={this.state.username}/>
<Form.Text className="text-muted">We'll never share your email with anyone else.</Form.Text></Form.Group><Form.Group controlId="formBasicPassword"><Form.Label>Password</Form.Label><Form.Control type="password" placeholder="Password"
value={this.state.password}/>
</Form.Group></Form>

Second step :

Now I am Going to create an “onChange” event handler. So on the input element let’s listen to the “onChange” event and assign a handler called “handleUsernameChange”.

<Form.Group><Form.Label>Username</Form.Label><Form.Control type="text" placeholder="Enter username"  
value={this.state.username} onChange={this.handleUsernameChange}/>
<Form.Text className="text-muted">We'll never share your email with anyone else.</Form.Text></Form.Group>
handleUsernameChange = (event) => {this.setState({username: event.target.value})}
handlePasswordChange = (event) => {this.setState({password: event.target.value})
<Form.Group controlId="formBasicPassword"><Form.Label>Password</Form.Label><Form.Control type="password" placeholder="Password" 
value={this.state.password} onChange={this.handlePasswordChange}/>
</Form.Group>
<Button variant="primary" type="submit">Submit</Button>
<Form onSubmit={this.handleSubmit}>
image of code with onChange event
image of code with onChange event
handleSubmit = (event) => {alert(`Hi ${this.state.username}`)}
the alert message with the form data.
the alert message with the form data.
The alert message with the form data
handleSubmit = (event) => {alert(`Hi ${this.state.username}`);event.preventDefault();}

Resources:

Forms-React

Sample Code:

react-form-app