Author avatar

Gaurav Singhal

How to Use Bootstrap Components with React.js

Gaurav Singhal

  • May 28, 2020
  • 12 Min read
  • 334 Views
  • May 28, 2020
  • 12 Min read
  • 334 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

React's support for a plethora of frameworks and libraries has allowed developers to build intriguing UI with minimal code and integrate external APIs for intricate functionalities. Bootstrap is the most popular CSS framework, used by a multitude of enterprises for single-page apps, and it's easy to use in React. This guide explores how to use Bootstrap components with Reactjs in primarily two ways: directly using native bootstrap components and using its component-based library, React Bootstrap.

Bootstrap Components

Bootstrap offers a variety of components that can be used in your markup templates to offer a seamless user experience throughout your app. Some of these include:

  • Alerts and toasts for an event's feedback

  • Modals, tooltips, collapsible, and popovers for displaying additional information

  • Forms, dropdowns, input groups, and select to handle user forms

  • Buttons, progress, and spinners to enhance the visual effects of the app

  • Lists, pagination, and breadcrumbs for displaying large amounts of content in a presentable format

  • Badges, cards, carousel, and jumbotrons for an attractive UI

This guide puts more emphasis on the implementation pattern so the same knowledge can be extended to any Bootstrap component in React.

Using Native Bootstrap with React

Start by creating an empty project.

Make sure you have Nodejs and npm installed in your machine (at least version 8 or higher) along with a code editor and a web browser (preferably Chrome or Firefox).

Create a new project using create-react-app:

1
npx create-react-app bootstrap-react
shell

Cleaning up the Template

Remove the logo, App.css, and all their imports from App.js. Clean out the starter template inside the App component. Your App.js should look like this:

1
2
3
4
5
6
7
8
9
10
11
import React from 'react';

function App() {
  return (
    <div className="App">
      <h2>Hello</h2>
    </div>
  );
}

export default App;
jsx

Setting up Bootstrap

First you need to get the Bootstrap styles. Head over to hte index.html file inside the public folder and add the following CDN inside the :

1
2
3
... 
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
...
html

Now all the Bootstrap style classes are ready to be used with JSX elements. Add the following script tags to enable JavaScript of the components .

1
2
3
4
5
6
7
...
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
...
html

To make sure the HTML body loads before loading these scripts, put them right above the closing of your index.html.

Using Alerts, Buttons and Form Components

To create a simple form using Bootstrap's form component, add the following code inside App.js .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React from 'react';

function App() {  
  return (
    <div className="App">
      <div className="container">
        <form >
            <label>Name: </label> 
            <input type = "text" className="form-control"/> 
            <input type = "submit"
            value = "Submit" className="btn btn-primary"/>
        </form> 
      </div>
    </div>
  );
}

export default App;
jsx

This will render the form on the page with an input field and a button. These components can be used by simply putting down their markup in your JSX template. However, to get these components in an event-driven format, your parent component should interact with them through the state.

Import the useState hook and create a state variable to keep track of an alert that will trigger when this form gets submitted. Set it initially false.

1
2
3
4
5
6
import React,{useState} from 'react';

function App() {
  let [alert,setAlert]=useState(false);
  ...
 }
jsx

Add a submit event that fires up when the form submits to set the alert's value to true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React,{useState} from 'react';

function App() {
  let [alert,setAlert]=useState(false);

  const handleSubmit=(e)=>{
    e.preventDefault();
    setAlert(true);
  }
  
  return (
    <div className="App">
      <div className="container">
        <form onSubmit = {handleSubmit} >
        ...
   )
 }
jsx

Last, conditionally output a Bootstrap alert component as a JSX element.

1
2
3
4
5
6
7
8
9
10
...
    {alert && <div class="alert alert-success alert-dismissible fade show" role="alert">
              <strong>Congrats!</strong> Your details have been submitted successfully
              <button type="button" class="close" data-dismiss="alert" aria-label="Close" 
              onClick={()=>{setAlert(false)}}>
                <span aria-hidden="true">&times;</span>
              </button>
          </div>
     }
 ...
jsx

Note that you need to set the value of the alert back to false after it is dismissed so the state variables stay inline with the alert event. The inline function on the closing button does this job.

Testing

Inside the root directory, run the following.

1
npm start

This will spin up a local development server (usually on port 3000) and you can see your form along with a button on the page. Click the submit button and an alert with a success message appears on the page. You can close the alert and fire it again through the submit button.

Disadvantages of Native Bootstrap

Using native bootstrap seems simple and convenient, but there are a few disadvantages associated with it. These include:

  • Unnecessarily long JSX, mitigating readability
  • Less modularity, making it difficult to debug
  • Customizing components might require external JavaScript or JQuery
  • Upgrading to newer versions requires manually updating all the CDNs and checking the code for depreciated classes and elements
  • Lack of component architecture

Using React Bootstrap

A solution to the above-mentioned problems is using React Bootstrap, a component-based library where everything is essentially a React component that can be rendered as a child component inside the component outputting it.

Setup

You can create a fresh CRA project by following the earlier steps up until the 'Setting up Bootstrap' section, or you can clean out the earlier template by undoing everything back to the 'Setting up Bootstrap' section. Your clean and empty App.js is good to go.

Installing React Bootstrap

Inside the root directory, run the following command to install the React Bootstrap library .

1
npm install react-bootstrap bootstrap

This will install both Bootstrap and React Bootstrap inside the project.

Using the Dropdown Component

For regular Bootstrap styles to work correctly, import the Bootstrap styles on top. You need to do this every time you use a React Bootstrap component.

1
import 'bootstrap/dist/css/bootstrap.min.css';
jsx

The above is equivalent to adding Bootstrap CDN in your index.html file. Now import the DropdownButton and Dropdown from react-bootstrap. This step is common regardless of the component you're using, but make sure you're importing the right and only required components.

1
2
import DropdownButton from 'react-bootstrap/DropdownButton';
import Dropdown from 'react-bootstrap/Dropdown'
jsx

Render them on the DOM inside App.js .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import DropdownButton from 'react-bootstrap/DropdownButton';        
import Dropdown from 'react-bootstrap/Dropdown'

function App() { 
  return (
    <div className="App container">
      <DropdownButton
      alignRight
      title="Dropdown right"
      id="dropdown-menu-align-right"
      >
              <Dropdown.Item eventKey="option-1">option-1</Dropdown.Item>
              <Dropdown.Item eventKey="option-2">option-2</Dropdown.Item>
              <Dropdown.Item eventKey="option-3">option 3</Dropdown.Item>
              <Dropdown.Divider />
              <Dropdown.Item eventKey="some link">some link</Dropdown.Item>
      </DropdownButton>
    </div>
  );
}

export default App;
jsx

You can see your Dropdown Component rendered with a list of items. Let's look at another example .

Using the Popover Components

Inside a clean and empty App.js, after importing Bootstrap styles, import Popover, OverlayTrigger, and Button from react-bootstrap .

1
2
3
import Popover from 'react-bootstrap/Popover';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import Button from 'react-bootstrap/Button';
jsx

To create a popover inside the popover component, render the Popover.Title component to indicate the title of the popover and Popover.Content component to indicate its content. Store this popover in a constant variable and output it inside the JSX template.

1
2
3
4
5
6
7
8
9
10
...
 const popover = (
    <Popover id="popover-basic">
      <Popover.Title as="h3">Popover title</Popover.Title>
      <Popover.Content>
        Popover content <strong>some strong content</strong> Normal content again
      </Popover.Content>
    </Popover>
  );
...
jsx

Output the popover inside an overlay and use the trigger prop to set the type of event the overlay listens for. The placement prop defines the position of your popover.

1
2
3
4
5
6
7
8
9
....
     return (
    <div className="App">
    <OverlayTrigger trigger="click" placement="right" overlay={popover}>
      <Button variant="success">Click to trigger popover</Button>
    </OverlayTrigger>
    </div>
  );
....
jsx

Finally, your App.js should look like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import Popover from 'react-bootstrap/Popover';
import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
import Button from 'react-bootstrap/Button';

function App() {
  const popover = (
    <Popover id="popover-basic">
      <Popover.Title as="h3">Popover title</Popover.Title>
      <Popover.Content>
        Popover content <strong>some strong content</strong> Normal content again
      </Popover.Content>
    </Popover>
  );

  return (
    <div className="App">
    <OverlayTrigger trigger="click" placement="right" overlay={popover}>
      <Button variant="success">Click to trigger popover</Button>
    </OverlayTrigger>
    </div>
  );
}

export default App;
jsx

Now you can see the popover button and the popover itself when you click on the button.

In case you get any depreciated warnings or errors, you can use the exact version of react-bootstrap that is used in this guide by updating your package.json file and running the command npm i .

1
2
3
4
....
"bootstrap": "^4.4.1",
"react-bootstrap": "^1.0.1",
....
json

Conclusion

Both methods discussed in this guide let you use bootstrap components in your React project, allowing you to develop your app faster without compromising the UI/UX. Choose the first one for smaller applications, as the fewer dependencies your project has, the smoother it runs. However, make sure you're keeping the code as modular as you can. For large applications, using React Bootstrap is an ideal choice.

2