Home/Blog/Programming/React Bootstrap tutorial: Upgrade React apps with a CSS framework
Home/Blog/Programming/React Bootstrap tutorial: Upgrade React apps with a CSS framework

React Bootstrap tutorial: Upgrade React apps with a CSS framework

14 min read
Aug 06, 2020

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Bootstrap, the most popular CSS framework, is a tool that we knew and loved when we were developing web pages using Vanilla JavaScript, Popper.js, and jQuery. We were able to get something off the ground super quickly and deliver prototypes faster to our stakeholders.

With Bootstrap, we can build responsive web pages with unique, built-in utilities.

With the advent of React, we needed to find something that would have the same functionality of Bootstrap but that could write directly to the Virtual DOM instead of the actual DOM. Enter React Bootstrap. Today, we will introduce you to React Bootstrap and show you how to build a web page.

We will cover:



Take your frontend skills to the next level.

Learn React skills step-by-step with Educatives’ advanced frontend learning path.

React for Front-End Developers


What is React Bootstrap?#

Bootstrap is the most popular CSS framework for responsive layouts. This open source toolkit with Sass variables, a responsive grid system, and tons of JavaScript plugins. It has now been rebuilt for React to integrate with React apps.

Bootstrap 4 depends on jQuery, but jQuery is not ideal for React, as it uses direct DOM manipulation while React uses a virtual DOM. React Bootstrap essentially replaces the Bootstrap JavaScript, so each component has been rebuilt to integrate beautifully with React. This gets rid of the need for jQuery.

Some of the components that React Bootstrap offers are:

  • Alters
  • Navbar
  • Dropdowns
  • Buttons
  • Tables
  • Pagination
  • Overlays
  • and more

Why use React Bootstrap?#

React Bootstrap is ideal for making responsive, fast React apps without unnecessary dependencies and downloads. Since Bootstrap was redesigned specifically for React, it has an almost “native” feel. Let’s look at some of the main reasons why you should use React Bootstrap for your apps.

Insertion to Virtual DOM#

React Bootstrap was introduced to allow Bootstrap components to be inserted to the Virtual DOM. These components are actual React Components, so there is no need to use jQuery or Popper.js to manipulate the DOM.

Bootstrap Stylesheet Allows for Consistency#

This package still relies on the stylesheet from the Bootstrap library, so all of the themes and such built-in to Bootstrap will continue to work for React Bootstrap as well.

Accessibility Out of Box#

Accessibility is super important when it comes to creating your web page. Crafting accessible components is even easier with React Bootstrap over vanilla Bootstrap.

Cleaner Code#

React Bootstrap uses React style components that include all the lengthy class information that Bootstrap would traditionally use. All of this is done under-the-hood and results in cleaner, more readable code.


Getting started with React Bootstrap#

This tutorial assumes that you have some knowledge building a React application. If you are unfamiliar with creating a React application, please read our React Beginners Tutorial to get up-to-date before progressing here. We’ll walk you step-by-step through the process of integrating React Bootstrap with your React apps. We’ll go over:

  • Add React Bootstrap to your app
  • Style and Stylesheet
  • Importing Components

Let’s jump in.


Add React Bootstrap to your app#

There are two ways to get started with React Bootstrap.


1. Package Manager#

Use npm or yarn to add the package to your project. In the root of your React application, in your terminal, use the following command for whichever package manager you are using:

npm install --save react-bootstrap bootstrap // npm
yarn add react-bootstrap bootstrap // yarn

2. CDN#

Copy and paste this CDN into the index.html file in your public folder. This script will go just above your closing body tag in your HTML.

<script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin>

Style & Bootstrap Stylesheet#

React Bootstrap does not come with any CSS. You will need to include some sort of stylesheet for your components to appear as they should on the screen. As with adding the package to your project you can do this one of two ways.


1. Import Stylesheet#

Add the import statement to your index.js file or your App.js file

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

Use the latest Bootstrap CDN to get the latest stylesheet and add it to the head of your index.html document, located in the public folder.

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

If you chose to use a package manager for adding the react-bootstrap and Bootstrap package, make sure you use the import statement to add the stylesheet. If you choose to use the CDN in the first step, choose to use the CDN for adding the stylesheet.

Note on Flexbox/Grid Support:

Because we are using a Bootstrap stylesheet with the React Bootstrap package, support for flexbox and Grid is ready-to-use out of the box. Components are completely responsive.


Using SASS?#

If you are using SASS, create an App.scss file and import Bootstrap’s SASS file to this file instead.

@import "~bootstrap/scss/bootstrap";

In your App.js file, you will instead import ./App.scss instead.


Customization of Styles#

If you would like to customize styles for your application, it is recommended to use SASS to do so. Create a custom.scss file to include your changes and then import the bootstrap stylesheet below your changes. Let’s look at an example of customization below.

// make your customizations
 
$theme-colors: (
   "info": pink,
   "danger": teal,
   "primary": purple
);
 
// import bootstrap stylesheet
 
@import "~bootstrap/scss/bootstrap";

Once you’ve made your customizations, you can import your custom.scss to the main SASS file.

@import "custom";

Importing Components#

According to React Bootstrap, you should refrain from importing the entire react-bootstrap library when you are importing a component. When declaring a component, instead only import what you actually need:


Single import from React Bootstrap#

//this only imports what we need
import Alert from 'react-bootstrap/Alert';
 
//this imports the whole library and uses object destructuring to grab the Button object
import { Alert } from 'react-bootstrap';

However, if you need multiple components from the react-bootstrap library, object destructuring is preferred to keep your code DRY.


Multiple imports from React Bootstrap#

//this
import { Alert, Form, Button, Card } from 'react-bootstrap';
 
//not this
import Alert from 'react-bootstrap/Alert';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';

The first way allows you to keep from repeating yourself by listing the import statements over and over again and only changing the component name.


Step-by-step example using React Bootstrap components#

Let’s apply what we’ve learned and build our own simple web application. We will construct a mock movie application using some of the most popular React Bootstrap components. The purpose of this section is to get a feel for how to get started and how to use the documentation to render components to the page.

Step 1: Setup and application structure#

The first thing we need to do is create our React application. If you’re unsure how to do that, please refer to the React documentation on how to get started. Refer to the Getting Started Section of this article to set up React Bootstrap.

Remember that when you use the CDN, you’ll need to use the CDN for react-bootstrap and then link to Bootstrap’s stylesheet. If you add these packages using the package manager, you can import the Bootstrap stylesheet to your index.js file.

In addition, you will want to add the axios package to your project. We will use it to make a GET request to a third-party API called TMDB for movie data.

Now let’s structure our application.

At a very high level, this will be the structure of our application as it appears in our App.js file:

<Container>
     <Navigation />
     <MovieTable movies={movies} />
     <MovieAccordion movies={movies} />
</Container>

<Container /> is a React Bootstrap component that envelops all of our React Components. I have separated this application into three basic sections.

  • First there is <Navigation />, where we will take a look at how the React Bootstrap <Navbar /> component works.
  • Second, we will take a look at the <Table /> and <Modal /> components in <MovieTable />.
  • Finally, the <Accordion /> component comes front and center.


Take your frontend skills to the next level.#

Learn React without scrubbing through videos or documentation. By the end of this path, you’ll be able to build interactive, professional-quality apps using React.

Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.

React for Front-End Developers


Step 2: Navbar#

In the return statement of our App component, we are going to create our overall <Container> that will hold our application. Then, we will add our <Navigation /> component. Import the Container from React Bootstrap using the guidelines from Getting Started above.

Create a separate file for the Navigation component, write out a skeleton functional component called Navigation, and export it. Import the file into App.js and make sure your <Navigation /> component is nestled between the opening and closing <Container /> tags.

Tip: If you have localhost running, you should be able to see that the component is wired up correctly. It’s a good idea to always wire up a basic component to make sure it works before going on to the next step.


Adding Navbar#

To add the React Bootstrap Navbar component, it’s easiest visit the documentation. For demonstration purposes, let’s take a look at the Color Scheme version of the Navbar to implement it into our code.

import React, { useState } from "react";
import {
Navbar,
Nav,
NavDropdown,
Form,
FormControl,
Button
} from "react-bootstrap";
import ModalLogin from "./ModalLogin";
const Navigation = () => {
const [modalShow, setModalShow] = useState(false);
return (
<Navbar bg="primary" variant="dark" expand="md">
<Navbar.Brand href="#home">Movies-App</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link
variant="transparent"
style={{ width: "50px" }}
onClick={() => setModalShow(true)}
>
Login
</Nav.Link>
<ModalLogin show={modalShow} onHide={() => setModalShow(false)} />
<Nav.Link href="#link">Link</Nav.Link>
<NavDropdown title="Sample Dropdown" id="basic-nav-dropdown">
<NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
<NavDropdown.Item href="#action/3.2">
Another action
</NavDropdown.Item>
<NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
<NavDropdown.Divider />
<NavDropdown.Item href="#action/3.4">
Separated link
</NavDropdown.Item>
</NavDropdown>
</Nav>
<Form inline>
<FormControl type="text" placeholder="Search" className="mr-sm-2" />
<Button variant="outline-light">Search</Button>
</Form>
</Navbar.Collapse>
</Navbar>
);
};
export default Navigation;

In this version of the Navbar component, I have added add a <ModalLogin /> component that contains React Bootstrap’s ` component and its constituent parts. This is one way to solve the issue of logging into sites. Remember that we are concentrating solely on the UI.

You can pick and choose the elements you need to use and incorporate them to create something that is unique to your needs.

Note: Do not try to reinvent the wheel when it comes to writing your logic! The point of this package is to get a prototype out the door quickly.


Step 3: Axios Call#

The rest of our components will need some data to display some information. For this application, we are using The Movie Database (TMDB) to grab some JSON data on today’s popular movies.

The TMDB API requires an account to make requests to their API. It’s fairly simple to set up. We will need that API Key in order to move forward. If you want to use another API, that’s fine, too. Just remember to change the syntax to match your chosen API.

For the purpose of this application, I will be using React Hooks to make the network calls and for state management. Remove the demo code from the App component and replace it with the needed code to make an axios call. The endpoint is given in the code below as URL:

const [movies, setMovies] = useState([]);
const [err, setErr] = useState("");
const [errBool, setErrBool] = useState(false);
const [loading, setLoading] = useState(true);
let URL = `https://api.themoviedb.org/3/movie/popular?api_key=${YOUR_API_KEY}&language=en-US&page=1`;
const fetchMovies = (url) => {
axios
.get(
url
)
.then(response => {
setMovies(response.data.results);
setLoading(false);
})
.catch(err => {
setErr(err.message);
setErrBool(true);
setLoading(false);
});
}
useEffect(() => {
fetchMovies(URL);
}, [URL]);

This code will make an HTTP GET Request to the TMDB endpoint that returns a promise. On fulfillment, we take the array of data returned to us and place it on state to be used in our application. The catch block will help with any error handling we might need.


Step 4: Create MovieTable component#

The goal for this component is to list some movie data in a table. In the final column, we will link to a modal that will display more information about the movie.


Create Table#

For this portion of our application, we will use the <Table /> component to create a set of rows and columns that will list information about today’s popular movies. To start, create a separate file for this component and import the Table and NavLink components from the react-bootstrap package.

Create a functional component that passes the props object as a parameter to the function and export that component so that you can import it to App.js.

In App.js, import this component and add it as a child to the <Container /> from the first step. Use the movies array from the axios call and pass it as props to this component. That will allow us to access the array and map over it to insert information into our cells.

Here, I decided to list the popularity, title, release_date, and overview properties. Because the overview itself was too long, I decided to create a modal to list some additional information about the movie.

import React, { useState } from "react";
import { Table, NavLink } from "react-bootstrap";
const MovieTable = props => {
let keys = ["popularity", "title", "release_date", "overview"];
const { movies } = props;
return (
<div style={{ width: "90%", margin: "0 auto" }}>
<h2 style={{textAlign: "center", margin: "20px auto auto"}}> Popular Movies for { new Date(Date.now()).toLocaleDateString()}</h2>
<Table
variant="default"
style={{ width: "100%", margin: "20px auto" }}
striped
bordered
responsive
>
<thead>
<tr>
{keys.map(heading => {
return <td key={heading}>{heading}</td>;
})}
</tr>
</thead>
<tbody>
{movies.map(movie => {
return (
<tr key={movie.id}>
<td>{movie.popularity}</td>
<td>{movie.title}</td>
<td>{movie.release_date}</td>
<td>modal will go here…</td>
</tr>
);
})}
</tbody>
</Table>
</div>
);
};
export default MovieTable;

Create Modal#

The modal is probably one of the trickier components in the library. Modals are basically pop-up windows that show up after a user interacts with the website in some way.

The only thing we need to get a modal up and running is the actual <Modal /> component. For this demonstration, we are also using the <Image /> component to display an image that represents each movie.

The makeup of the <Modal /> mimics the structure of the <body> of an HTML document:

  • The header of the modal tells us why we have the modal
  • The main body of the modal
  • The footer of the modal

We will be handling the modal’s state (open or closed) in the <MovieTable /> component. If you set the showModal state to true, it will open all of the modals at once and pile them on top of each other. You have to figure out a way to get one modal to open at a time.

Here is one way to do that:

import React from "react";
import { Modal, Image } from "react-bootstrap";
const ModalOverview = props => {
return (
<Modal
{...props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header>
<Image fluid src={`https://image.tmdb.org/t/p/original${props.movie.backdrop_path}`} alt={props.movie.title} />
</Modal.Header>
<Modal.Body>
<Modal.Title id="contained-modal-title-vcenter">
{props.movie.title} <span style={{fontSize: "1rem", fontStyle: "italic"}}>{new Date(props.movie.release_date).toLocaleDateString()}</span>
</Modal.Title>
<p>{props.movie.overview}</p>
<p> Popularity: {props.movie.popularity} </p>
<p> Votes: {props.movie.vote_count}</p>
</Modal.Body>
</Modal>
);
};
export default ModalOverview;

Let’s see how our code looks so far. Below in the <MovieTable /> component, we track the state of the modal by setting the modalShow variable to the movie id that has been passed.

To make sure only one modal is displayed at a time, we ask if the movie.id is equal to the movie.id that’s been set to modalShow. Because only one id would be equal to what’s been set, only that modal will show when it has been clicked.

// Modal state in MovieTable
import React, { useState } from "react";
import { Table, NavLink } from "react-bootstrap";
import ModalOverview from "./ModalOverview";
const MovieTable = props => {
const [modalShow, setModalShow] = useState(false);
let keys = ["popularity", "title", "release_date", "overview"];
const { movies } = props;
return (
<div style={{ width: "90%", margin: "0 auto" }}>
<h2 style={{textAlign: "center", margin: "20px auto auto"}}> Popular Movies for { new Date(Date.now()).toLocaleDateString()}</h2>
<Table
variant="default"
style={{ width: "100%", margin: "20px auto" }}
striped
bordered
responsive
>
<thead>
<tr>
{keys.map(heading => {
return <td key={heading}>{heading}</td>;
})}
</tr>
</thead>
<tbody>
{movies.map(movie => {
return (
<tr key={movie.id}>
<td>{movie.popularity}</td>
<td>{movie.title}</td>
<td>{movie.release_date}</td>
<td>
<NavLink
value={movie.id}
onClick={() => {
setModalShow(movie.id);
}}
>Details
</NavLink>
<ModalOverview
movie={movie}
show={modalShow === movie.id}
onHide={() => setModalShow(false)}
/>
</td>
</tr>
);
})}
</tbody>
</Table>
</div>
);
};
export default MovieTable;

Step 5: Create MovieAccordion component#

In this component, we will create an accordion, a component that hides information until the user clicks on its heading. We will use the same information from the same axios request that was called when the component mounted.

Explained: The accordion is a UI technique that combines the idea of buttons with the idea of cards and creates an element that is either opened or closed.

Create s component that will hold the Accordion component following the same convention as you did for the <MovieTable /> component. We will bring in the Accordion and Card components.

When rendering the component that has the accordion as part of the larger App component, be sure to pass the movies state to the component so that the information can be used for your accordion.

import React from 'react';
import { Accordion, Card, Image } from "react-bootstrap";
const MovieAccordion = props => {
const { movies } = props;
return (
<Accordion style={{width: "90%", margin: "0px auto 40px", cursor: "pointer"}}>
{
movies.map(movie => {
return (
<Card key={movie.id}>
<Accordion.Toggle as={Card.Header} eventKey={movie.id}>
{movie.title}
</Accordion.Toggle>
<Accordion.Collapse eventKey={movie.id}>
<Card.Body>
<Image fluid src={`https://image.tmdb.org/t/p/original${movie.backdrop_path}`} alt={movie.title} />
<h5 style={{marginBottom: "0"}}>{movie.title}</h5>
<p style={{fontSize: ".8rem", fontStyle: "italic"}}>Release Date: {new Date(movie.release_date).toLocaleDateString()}</p>
<p>{movie.overview}</p>
</Card.Body>
</Accordion.Collapse>
</Card>
)
})
}
</Accordion>
);
}
export default MovieAccordion;

Be sure that the eventKey for the toggle and collapse match if you hardcode your Accordion component. Here, I mapped over the movies array to return Cards that contain the information for each movie. Be sure that the eventKey for both parts of the accordion point to the same property.


Wrapping up and next steps#

You’ve just created your first application using React and React Bootstrap! Well done! React Bootstrap is pretty straightforward once you get the hang of it.

There’s still a lot more to learn about both React and Bootstrap. Some of the more advanced concepts in React that you’ll want to master are:

  • Using TypeScript with React
  • React design patterns
  • React Tracked
  • Firebase and React
  • and more

To get started with these advanced React concepts, I recommend Educative’s React for Front-End Developers Learning Path for React developers, that walks you through intermediate and advanced modules on React and app development and deployment. By the end, you’ll be able to build interactive, professional-quality apps.

Happy learning!


Continue reading about React and CSS#


Written By:
Christina Kopecky
 
Join 2.5 million developers at
Explore the catalog

Free Resources