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 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
This guide puts more emphasis on the implementation pattern so the same knowledge can be extended to any Bootstrap component in 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:
1npx create-react-app bootstrap-react
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:
1import React from 'react';
2
3function App() {
4 return (
5 <div className="App">
6 <h2>Hello</h2>
7 </div>
8 );
9}
10
11export default App;
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<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
3...
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<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
3
4<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
5
6<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
7...
To make sure the HTML body loads before loading these scripts, put them right above the closing of your index.html.
To create a simple form using Bootstrap's form component, add the following code inside App.js
.
1import React from 'react';
2
3function App() {
4 return (
5 <div className="App">
6 <div className="container">
7 <form >
8 <label>Name: </label>
9 <input type = "text" className="form-control"/>
10 <input type = "submit"
11 value = "Submit" className="btn btn-primary"/>
12 </form>
13 </div>
14 </div>
15 );
16}
17
18export default App;
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.
1import React,{useState} from 'react';
2
3function App() {
4 let [alert,setAlert]=useState(false);
5 ...
6 }
Add a submit event that fires up when the form submits to set the alert's value to true.
1import React,{useState} from 'react';
2
3function App() {
4 let [alert,setAlert]=useState(false);
5
6 const handleSubmit=(e)=>{
7 e.preventDefault();
8 setAlert(true);
9 }
10
11 return (
12 <div className="App">
13 <div className="container">
14 <form onSubmit = {handleSubmit} >
15 ...
16 )
17 }
Last, conditionally output a Bootstrap alert component as a JSX element.
1...
2 {alert && <div class="alert alert-success alert-dismissible fade show" role="alert">
3 <strong>Congrats!</strong> Your details have been submitted successfully
4 <button type="button" class="close" data-dismiss="alert" aria-label="Close"
5 onClick={()=>{setAlert(false)}}>
6 <span aria-hidden="true">×</span>
7 </button>
8 </div>
9 }
10 ...
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.
Inside the root directory, run the following.
1npm 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.
Using native bootstrap seems simple and convenient, but there are a few disadvantages associated with it. These include:
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.
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.
Inside the root directory, run the following command to install the React Bootstrap library .
1npm install react-bootstrap bootstrap
This will install both Bootstrap and React Bootstrap inside the project.
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.
1import 'bootstrap/dist/css/bootstrap.min.css';
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.
1import DropdownButton from 'react-bootstrap/DropdownButton';
2import Dropdown from 'react-bootstrap/Dropdown'
Render them on the DOM inside App.js
.
1import React from 'react';
2import 'bootstrap/dist/css/bootstrap.min.css';
3import DropdownButton from 'react-bootstrap/DropdownButton';
4import Dropdown from 'react-bootstrap/Dropdown'
5
6function App() {
7 return (
8 <div className="App container">
9 <DropdownButton
10 alignRight
11 title="Dropdown right"
12 id="dropdown-menu-align-right"
13 >
14 <Dropdown.Item eventKey="option-1">option-1</Dropdown.Item>
15 <Dropdown.Item eventKey="option-2">option-2</Dropdown.Item>
16 <Dropdown.Item eventKey="option-3">option 3</Dropdown.Item>
17 <Dropdown.Divider />
18 <Dropdown.Item eventKey="some link">some link</Dropdown.Item>
19 </DropdownButton>
20 </div>
21 );
22}
23
24export default App;
You can see your Dropdown Component rendered with a list of items. Let's look at another example .
Inside a clean and empty App.js
, after importing Bootstrap styles, import Popover, OverlayTrigger, and Button from react-bootstrap
.
1import Popover from 'react-bootstrap/Popover';
2import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
3import Button from 'react-bootstrap/Button';
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 const popover = (
3 <Popover id="popover-basic">
4 <Popover.Title as="h3">Popover title</Popover.Title>
5 <Popover.Content>
6 Popover content <strong>some strong content</strong> Normal content again
7 </Popover.Content>
8 </Popover>
9 );
10...
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 return (
3 <div className="App">
4 <OverlayTrigger trigger="click" placement="right" overlay={popover}>
5 <Button variant="success">Click to trigger popover</Button>
6 </OverlayTrigger>
7 </div>
8 );
9....
Finally, your App.js
should look like this
:
1import React from 'react';
2import 'bootstrap/dist/css/bootstrap.min.css';
3import Popover from 'react-bootstrap/Popover';
4import OverlayTrigger from 'react-bootstrap/OverlayTrigger';
5import Button from 'react-bootstrap/Button';
6
7function App() {
8 const popover = (
9 <Popover id="popover-basic">
10 <Popover.Title as="h3">Popover title</Popover.Title>
11 <Popover.Content>
12 Popover content <strong>some strong content</strong> Normal content again
13 </Popover.Content>
14 </Popover>
15 );
16
17 return (
18 <div className="App">
19 <OverlayTrigger trigger="click" placement="right" overlay={popover}>
20 <Button variant="success">Click to trigger popover</Button>
21 </OverlayTrigger>
22 </div>
23 );
24}
25
26export default App;
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"bootstrap": "^4.4.1",
3"react-bootstrap": "^1.0.1",
4....
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.