Menu

Create Form UI using React-Bootstrap

RohitG 2 years ago 2 288

In this article, we will create a form UI using React Bootstrap.

To learn to

  1. Create a simple React Form UI using Bootstrap and React, visit here.
  2. Add JSX to React Form UI, visit here.

React Bootstrap

React-Bootstrap is a comprehensive React re-implementation of the Bootstrap components. It is not dependent on bootstrap.js or jQuery. You already have everything you need if you have React and React-Bootstrap installed.

jQuery methods and events are created by directly modifying the DOM. React, on the other hand, employs state updates to update the virtual DOM. By embedding Bootstrap capabilities into React’s virtual DOM, React-Bootstrap delivers a more dependable approach.

Given below are code snippets that show the difference between Bootstrap and React-Bootstrap.

The below code results in a simple alert message at the click of a button.

Bootstrap
import * as React from 'react';

function Example()  {
  return (
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <strong>Oh snap! You got an error!</strong> 
      <p> 
        Change this and that and try again.
      </p>
      <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
  )
}
React-Bootstrap
import * as React from 'react';
import Alert from 'react-bootstrap/Alert';

function Example() {
  return (
    <Alert dismissible variant="danger">
      <Alert.Heading>Oh snap! You got an error!</Alert.Heading>
      <p>
        Change this and that and try again.
      </p>
    </Alert>
  )
}

In the above code, we use “dismissible” and variant=”danger” to create a cancellable Error Alert box.

Install React-Bootstrap

npm install react-bootstrap --save

App.js

Once you are done installing add the following to your App.js

import 'bootstrap/dist/css/bootstrap.min.css';
import { Form, InputGroup, Row, Button } from 'react-bootstrap';
import { useState } from 'react';

I will be using the useState hook to manage the form elements’ values. You can read about React useState Hook here.

I will create a “form” hook and add attributes corresponding to each input field I create, initializing each a null value.

const [form, setForm] = useState({
    first_name: '',
    last_name: '',
    mobile: '',
    email: '',
    address1: '',
    address2: '',
    city: '',
    a_state: '',
    pin: '',
    menu: '',
    order: ''
  });

Now we need to create a function that will change the value of “form” attributes to the entered values.

const handleChange = (e) => {
    setForm({ ...form, [e.target.name]: e.target.value });
  }

Since each form UI has a submit button, we will now code for submitButton(). Under which, we will add the following functionalities

  1. Prevents any default events to take place.
  2. Log all the entered values.
  3. Clear the contents of the form UI.
const submitButton = (e) => {
    e.preventDefault();
    console.log(form);
    resetButton()
  }

To clear the contents of Form UI, we will call the setForm() and set all the attribute values to empty.

const resetButton = () => {
    setForm({
      first_name: '',
      last_name: '',
      mobile: '',
      email: '',
      address1: '',
      address2: '',
      city: '',
      a_state: '',
      pin: '',
      menu: '',
      order: ''
    });
  }

You can read about React Bootstrap components below

  1. Form
  2. InputGroup
  3. Row
  4. Button

Note: Install Bootstrap as I will be using Bootstrap classes.

<Form className='container mt-3 mb-3'>

Using React-Bootstrap Form component, we are rending a Form, and using ‘container’ and ‘mb-3’ bootstrap classes

<Row className='mb-3'>

We use the React-Bootstrap Row component to align particular components horizontally.

<Form.Group controlId="formBasicEmail" className="col col-sm-6">

We use React-Bootstrap Form.Group to group individual components into one component. Here controlID is used instead of “htmlFor”.

<Form.Label>First Name</Form.Label>

Form.label is used to provide a text label as a component.

<Form.Control type="name" name="first_name" value="{form.first_name}" onChange="{handleChange}" className="form-control" />

We use Form.Control as an alternative to <input> tag.

  1. type – declares the type of input we want like text, password, etc.
  2. name – ID of the component used by JSX
  3. value – default value of component
  4. onChange – specifies the action to be taken when any change is made
  5. className- Bootstrap classes used
<InputGroup>
   <InputGroup.Text id="basic-addon1">+91</InputGroup.Text>
   <Form.Control aria-label="Mobile Number" type="mobile" aria-describedby="basic-addon1" className="form-control" name="mobile" value="{form.mobile}" onChange="{handleChange}" />
</InputGroup>

We use InputGroup to create a group of Input Components.

InputGroup.Text is used to provide unedible input elements with the desired text.

  1. aria-label – used to provide the label
  2. type – specifies the type of data that will be added
  3. aria-describedby – specifies the ID of the element
  4. className – bootstrap classes to be used
  5. name- ID of the component to be used by JSX
  6. values- specifies the value need to be set
  7. onChange – specifies the action to be done if any change happens
<Form.Select defaultValue="Choose..." className="form-control" name="a_state" value="{form.a_state}" onChange="{handleChange}">
   <option value="Choose...">Choose...</option>
   <option value="Delhi">Delhi</option>
   <option value="Bombay">Bommbay</option>
   <option value="New York">New York</option>
   <option value="Kashmir">Kashmir</option>
</Form.Select>

Form.Select is the React-Bootstrap alternative of dropdowns.

  1. defaultValue – specifies the default value to be set
  2. className – bootstrap classes to be used
  3. name – ID of the component to be used by JSX
  4. values- specifies the value need to be set
  5. onChange – specifies the action to be done if any change happens

<option> is used to add values to the dropdown.

<Form.Control as="textarea" rows="{3}" className="form-control" name="order" value="{form.order}" onChange="{handleChange}" />

“as=textarea” is used to create a multi-line input component.

<button type="submit" onClick="{submitButton}" className="me-4 btn btn-success btn-lg btn-block">Submit</button>

<button> is used to insert a button component.

  1. type- specifies the type of button we want to create
  2. onClick- specifies the action to be performed on click
  3. className- bootstrap classes to be used

Given below is the full code

<form className="container mt-3 mb-3">
    <Row className="mb-3">
        <Form.Group controlId="formBasicEmail" className="col col-sm-6">
            <Form.Label>First Name</Form.Label>
            <Form.Control type="name" name="first_name" value="{form.first_name}" onChange="{handleChange}" className="form-control" />
        </Form.Group>
        <Form.Group controlId="formBasicEmail" className="col col-sm-6">
            <Form.Label>Last Name</Form.Label>
            <Form.Control type="name" name="last_name" value="{form.last_name}" onChange="{handleChange}" className="form-control" />
        </Form.Group>
    </Row>
    <Row className="mb-3">
        <Form.Group controlId="formBasicMobile" className="col col-sm-6">
            <Form.Label>Mobile Number</Form.Label>
            <InputGroup>
                <InputGroup.Text id="basic-addon1">+91</InputGroup.Text>
                <Form.Control aria-label="Mobile Number" type="mobile" aria-describedby="basic-addon1" className="form-control" name="mobile" value="{form.mobile}" onChange="{handleChange}" />
            </InputGroup>
        </Form.Group>
        <Form.Group controlId="formBasicEmail" className="col col-sm-6">
            <Form.Label>Email</Form.Label>
            <InputGroup>
                <Form.Control aria-label="Recipient's username" aria-describedby="basic-addon2" type="email" name="email" value="{form.email}" onChange="{handleChange}" />
                <InputGroup.Text id="basic-addon2">@gmail.com</InputGroup.Text>
            </InputGroup>
        </Form.Group>
    </Row>
    <Row className="mb-3">
        <Form.Group className=" col col-sm-6" controlId="formGridAddress1">
            <Form.Label>Address</Form.Label>
            <Form.Control className="form-control" type="text" name="address1" value="{form.address1}" onChange="{handleChange}" />
        </Form.Group>
        <Form.Group className="col col-sm-6" controlId="formGridAddress2">
            <Form.Label>Address 2</Form.Label>
            <Form.Control className="form-control" name="address2" value="{form.address2}" onChange="{handleChange}" type="text" />
        </Form.Group>
    </Row>
    <Row className="mb-3">
        <Form.Group controlId="formGridCity" className="col col-sm-4">
            <Form.Label>City</Form.Label>
            <Form.Control className="form-control" type="text" name="city" value="{form.city}" onChange="{handleChange}" />
        </Form.Group>
        <Form.Group controlId="formGridState" className="col col-sm-4">
            <Form.Label>State</Form.Label>
            <Form.Select defaultValue="Choose..." className="form-control" name="a_state" value="{form.a_state}" onChange="{handleChange}">
                <option value="Choose...">Choose...</option>
                <option value="Delhi">Delhi</option>
                <option value="Bombay">Bommbay</option>
                <option value="New York">New York</option>
                <option value="Kashmir">Kashmir</option>
            </Form.Select>
        </Form.Group>
        <Form.Group controlId="formGridpin" className="col col-sm-4">
            <Form.Label>Pin Code</Form.Label>
            <Form.Control className="form-control" type="pin" name="pin" value="{form.pin}" onChange="{handleChange}" />
        </Form.Group>
    </Row>
    <Row className="mb-3">
        <Form.Group controlId="formGridCheckbox" className="col col-sm-6">
            <Form.Label>Menu</Form.Label>
            <Form.Select defaultValue="Choose..." className="form-control" name="menu" value="{form.menu}" onChange="{handleChange}">
                <option value="Choose...">Choose...</option>
                <option value="Veg Biryani">Veg Biryani</option>
                <option value="BBQ Chicken Wings">BBQ Chicken Wings</option>
                <option value="Rasmalai">Rasmalai</option>
                <option value="Beer">Beer</option>
            </Form.Select>
        </Form.Group>
        <Form.Group controlId="formGridlabel" className="col col-sm-6">
            <Form.Label>Order Details</Form.Label>
            <Form.Control as="textarea" rows="{3}" className="form-control" name="order" value="{form.order}" onChange="{handleChange}" />
        </Form.Group>
    </Row>
    <Row className="mb-3">
        <Form.Group controlId="formGridCheckbox" className="col col-sm-6">
            <button type="submit" onClick="{submitButton}" className="me-4 btn btn-success btn-lg btn-block">Submit</button>
            <button type="reset" onClick="{resetButton}" className="me-4 btn btn-danger btn-lg btn-block">Cancel</button>
        </Form.Group>
    </Row>
</form>

After making all the above-mentioned changes, execute the following command

npm start

After which you will get the following UI, in which you can enter your details.

Conclusion

Thanks for reading, hope you got answers to some of your questions and learned how to create a simple Form UI in React.

Visit Let’s React to learn more about React.

– Advertisement – BuzzMag Ad
Written By

2 Comments

2 Comments

  1. jose says:

    Hi, I did the same example but for Form.Select I have a problem, state is not update when onChange event is fired.

Leave a Reply

Your email address will not be published. Required fields are marked *