Editor’s note: This post was updated on 30 August 2023 to update code blocks according to React 18 and add information about customizing Bootstrap 5 with Sass.
The increasing popularity of single-page applications over the last few years has led to an influx of JavaScript frameworks, the most popular of which being React. This has coincided with the emergence of CSS frameworks designed to help developers build responsive web apps.
If React is the most-used JavaScript framework for building web applications, Bootstrap is the most popular CSS framework, powering millions of websites on the internet. In this tutorial, we will review how to add Bootstrap to React according to the latest version of both frameworks. We’ll also learn how to use the React-Bootstrap and Reactstrap packages to provide Bootstrap components for a React application.
Jump ahead:
If you’re just getting started with these frameworks, I’d suggest skimming through the official React and Bootstrap documentation. I’d also encourage you to watch the comprehensive video below for a deeper dive:
How to use Bootstrap with React
0:00 Introduction 3:57 Getting started with Bootstrap 6:14 Importing the Bootstrap style sheet 9:50 Applying the toast function for notifications 13:20 Rendering a card with Bootstrap Repo: https://github.com/karlhadwen/bootstrap-react Try LogRocket for free: https://logrocket.com/?yt10 LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser.
There are many JavaScript frameworks you can choose from, including Angular, React, Vue.js, Ember, and so many more. Thanks to these options, it’s no longer necessary to use a DOM library, such as jQuery, to build web apps.
In addition, if you’re a frontend developer, you’ve almost certainly used or at least heard about Bootstrap, Foundation, and Bulma. These are all responsive (mobile-first) CSS frameworks with robust features and built-in utilities.
As we mentioned, React and Bootstrap are currently the most popular JavaScript and CSS frameworks, respectively. Developers use React and Bootstrap not only because of their widespread popularity but also to avoid the hassle of building web applications from scratch. Both libraries are highly modular, which makes it easy to add new features and functionality to web applications. As a result, React and Bootstrap are popular choices for developers who are looking to build high-quality web applications quickly and efficiently.
In the following section, we’ll review how to add Bootstrap to React apps.
The three most common ways to add Bootstrap to your React app are:
Let’s go over each of these in more detail.
The Bootstrap CDN is the easiest way to add Bootstrap to your React app. You just have to include a link to the CDN in the head section of your application entry file; no extra installation or downloads are required. In a typical React application created with Create React App, that would be in the public/index.html
file.
Because we want to include the current stable version of Bootstrap, our link will look like this:
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha256-2TnSHycBDAm2wpZmgdi0z81kykGPJAkiUY+Wf97RbvY=" crossorigin="anonymous">
If your project also requires using the JavaScript components that ship with Bootstrap, such as toggling a modal, dropdown, or navbar, we’ll need to link the bootstrap.bundle.min.js
file, which comes precompiled with Popper.js.
We can do this by placing the following <script>
tag near the end of our entry markup page, right before the closing </body>
tag:
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha256-gOQJIa9+K/XdfAuBkg2ONAdw5EnQbokw/s2b8BqsRFg=" crossorigin="anonymous"></script>
After linking the Bootstrap CSS and bundled Javascript CDNs, the complete code for our public/index.html
file will look like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <title>React App</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" /> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous" ></script> </body> </html>
Now you can start using the built-in Bootstrap classes and JavaScript components in your React app components.
If you are using a build tool or a module bundler such as webpack or Vite, this will be the preferred option for adding Bootstrap to your React application. You can easily start the installation by running the following:
npm install bootstrap # OR yarn add bootstrap
This command will install the most recent version of Bootstrap. Once the installation is complete, we can include it in our app’s entry file:
// Bootstrap CSS import "bootstrap/dist/css/bootstrap.min.css"; // Bootstrap Bundle JS import "bootstrap/dist/js/bootstrap.bundle.min";
In the case of a project built with CRA or Vite, that would be in the src/index.js
and src/main.js
files, respectively. The entire file’s contents will look like this after the import:
import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; // Bootstrap CSS import "bootstrap/dist/css/bootstrap.min.css"; // Bootstrap Bundle JS import "bootstrap/dist/js/bootstrap.bundle.min"; const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <App /> </React.StrictMode> );
As shown in the code above, we’ve imported both Bootstrap CSS and its associated JavaScript file. We’ve also made sure to import Bootstrap before our main CSS file index.css
so as to make it easier to alter Bootstrap’s default styling with this file as desired.
Once this process is complete, we can start using the built-in Bootstrap classes in our React app components.
The third way to add Bootstrap to a React app is to use a package that has prebuilt Bootstrap components designed to work as React components.
The benefit of this method is that practically all Bootstrap components are bundled as a React component in these libraries. For example, a full Bootstrap modal component can now be easily imported as <Modal />
in our React application.
While there are various packages you can use to install Bootstrap in React, the two most popular are React-Bootstrap and Reactstrap. These packages share very similar characteristics. We’ll go into detail about each package later in this tutorial.
Bootstrap can be used directly on elements and components in your React app by applying the built-in classes as you would any other class. To demonstrate the use of Bootstrap classes and components, let’s create a basic theme switcher React component:
As shown in this demo, we are using a dropdown component that is available in Bootstrap to implement our theme switcher. We are also using the built-in button
classes to set the size and color of the dropdown button.
Now, let’s write the code for our theme switcher component. Ensure you have a React app already set up. In your src
folder, create a new file called ThemeSwitcher.js
for the component and add the following code snippet to it:
import { useState } from "react"; const ThemeSwitcher = () => { const [theme, setTheme] = useState(null); const resetTheme = () => { setTheme(null); }; const themeClass = theme ? theme.toLowerCase() : "secondary"; return ( <> <div className={`text-capitalize h1 mb-4 w-100 text-center text-${themeClass}`} > {`${theme || "Default"} Theme`} </div> <div className="btn-group"> <button className={`text-capitalize btn btn-${themeClass} btn-lg"`} type="button"> {theme ? theme + " theme" : "Choose Theme"} </button> <button type="button" className={`btn btn-lg btn-${themeClass} dropdown-toggle dropdown-toggle-split`} data-bs-toggle="dropdown" aria-expanded="false" > <span className="visually-hidden">Toggle Dropdown</span> </button> <div className="dropdown-menu"> <a className="dropdown-item" onClick={() => setTheme("primary")}> Primary Theme </a> <a className="dropdown-item" onClick={() => setTheme("danger")}> Danger Theme </a> <a className="dropdown-item" onClick={() => setTheme("success")}> Success Theme </a> <div className="dropdown-divider"></div> <a className="dropdown-item" href="#" onClick={() => resetTheme()}> Default Theme </a> </div> </div> </> ); }; export default ThemeSwitcher;
In the code above, we created a very simple theme switcher component using Bootstrap’s dropdown component and a few built-in classes.
Using React’s useState
Hook, we created a state theme
and set its initial value to null
, as well as defined the setTheme
method to modify this state. Then we created a resetTheme
function that resets the theme’s value to null
.
Next, in our component markup, we rendered a Bootstrap dropdown with four dropdown items. The first three items allow us to switch between different themes: primary
, danger
, and success
, and the last dropdown item allows us to reset the theme value to null
using the resetTheme()
function.
In this example, we see how easy it is to use Bootstrap’s built-in classes and components in our React app. Now, to further understand how the React Bootstrap packages work, let’s recreate our theme switcher application using the components provided by React-Bootstrap and Reactstrap while writing limited code.
Assuming that you already have a React application set up, let’s install the React-Bootstrap package in our app with the following command:
npm install react-bootstrap bootstrap
It’s worth mentioning that React-Bootstrap doesn’t come pre-installed with Bootstrap itself. The package only exports common Bootstrap classes as React components, which is why we could also see Bootstrap appended in the installation command above.
Once we have React-Bootstrap installed, we are able to import any component. For example, importing the Button
component would look like this:
import { Button } from 'react-bootstrap';
To continue with our theme switcher example, let’s create a new file named ThemeSwitcher.js
in the src
directory of our project and put the following contents in it:
import { useState } from "react"; import { Button, ButtonGroup, Dropdown } from "react-bootstrap"; const ThemeSwitcher = () => { const [theme, setTheme] = useState(null); const resetTheme = () => { setTheme(null); }; return ( <div className="mb-2"> <Dropdown as={ButtonGroup} size="lg"> <Button className="text-capitalize" variant={theme ? theme : "secondary"} > {theme ? theme : "Default"} </Button> <Dropdown.Toggle split variant={theme ? theme : "secondary"} id="dropdown-split-basic" /> <Dropdown.Menu> <Dropdown.Item eventKey="1" onClick={() => setTheme("primary")}> Primary </Dropdown.Item> <Dropdown.Item eventKey="2" onClick={() => setTheme("danger")}> Danger </Dropdown.Item> <Dropdown.Item eventKey="3" onClick={() => setTheme("success")}> Success </Dropdown.Item> <Dropdown.Divider /> <Dropdown.Item eventKey="4" onClick={resetTheme}> Default Theme </Dropdown.Item> </Dropdown.Menu> </Dropdown> </div> ); }; export default ThemeSwitcher;
In the code above, we tried to replicate our initial example as much as possible using React-Bootstrap. We imported three components from the React-Bootstrap package; namely, Button
, ButtonGroup
, and Dropdown
. And just like we did previously, we used the useState
Hook to create our theme state and defined a function that set the value of theme
to null
.
Finally, we will modify the src/App.js
file to look like the following:
import ThemeSwitcher from "./ThemeSwitcher"; function App() { return ( <div className="App min-vh-100 d-flex justify-content-center align-items-center"> <div> <ThemeSwitcher /> </div> </div> ); } export default App;
The only change we’ve made to this file is getting rid of the CRA starter page and making it render our ThemeSwitcher
component instead.
Now, if we run the app with the command yarn start
or npm start
, it should start on port 3000
and should look like the following demo:
The Reactstrap package is quite similar to React-Bootstrap, with minor differences in things such as component and prop names. React-Bootstrap is a little older than Reactstrap, which may have contributed to its wider adoption range.
We can easily add Reactstrap to our React project with the command below:
npm install bootstrap reactstrap # OR yarn add bootstrap reactstrap
The code for our ThemeSwitcher
component will look like this:
import { useState } from "react"; import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem, } from "reactstrap"; const Theme = () => { const [theme, setTheme] = useState(null); const [dropdownOpen, setdropdownOpen] = useState(false); const resetTheme = () => { setTheme(null); }; return ( <div className="mb-2"> <div className={`text-capitalize h1 mb-4 w-100 text-center text-${ theme ? theme.toLowerCase() : "secondary" }`} > {`${theme || "Default"}`} </div> <div className="d-flex justify-content-center p-5"> <Dropdown isOpen={dropdownOpen} toggle={() => setdropdownOpen(!dropdownOpen)} > <DropdownToggle color={theme} caret> Dropdown </DropdownToggle> <DropdownMenu> <DropdownItem onClick={() => setTheme("primary")}> Primary Theme </DropdownItem> <DropdownItem onClick={() => setTheme("danger")}> Danger Theme </DropdownItem> <DropdownItem onClick={() => setTheme("success")}> Success Theme </DropdownItem> <DropdownItem divider /> <DropdownItem onClick={resetTheme}>Default Theme</DropdownItem> </DropdownMenu> </Dropdown> </div> </div> ); }; export default Theme;
When comparing both code files from the Reactstrap and React-Bootstrap examples, particularly the action that triggers our dropdown toggle, we can see that Reactstrap leverages React Hooks to use React features more, while React-Bootstrap relies more on component properties.
If we run the app now with the command yarn start
or npm start
, our app should start on port 3000
and look like the following demo:
Now that we have our basic theme switcher, let’s try to use as many Bootstrap classes and components as possible to add more details to our app. We will also use Reactstrap to add Bootstrap to React.
Let’s start by creating a new app with Vite:
npm create vite@latest sample-app --template react
Next, install the dependencies as follows:
npm install axios bootstrap reactstrap
Notice that we installed Axios as a dependency. Axios is a promise-based HTTP client for the browser and Node.js. It will enable us to fetch posts from the Bacon Ipsum JSON API.
Let’s make a little modification to the src/index.js
file to include the Bootstrap minified CSS and JavaScript files. It should look like the following snippet:
import React from "react"; import ReactDOM from "react-dom/client"; import App from './App.jsx' import './index.css' // Bootstrap CSS import "bootstrap/dist/css/bootstrap.min.css"; // Bootstrap Bundle JS import "bootstrap/dist/js/bootstrap.bundle.min"; ReactDOM.createRoot(document.getElementById('root')).render( <React.StrictMode> <App /> </React.StrictMode>, )
Next, we’ll create a new directory named components
inside the src
directory of our project. In this new components
directory, create a file called Header.js
and update it with the following contents:
import logo from '../logo.svg'; import { Container, Row, Col, Form, Input, Button, Navbar, Nav, NavbarBrand, NavLink, NavItem, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; const AVATAR = 'https://www.gravatar.com/avatar/429e504af19fc3e1cfa5c4326ef3394c?s=240&d=mm&r=pg'; const Header = () => ( <header> <Navbar fixed="top" color="light" light expand="xs" className="border-bottom border-gray bg-white" style={{ height: 80 }}> <Container> <Row g-0 className="position-relative w-100 align-items-center"> <Col className="d-none d-lg-flex justify-content-start"> <Nav className="mrx-auto" navbar> <NavItem className="d-flex align-items-center"> <NavLink className="font-weight-bold" href="/"> <img src={AVATAR} alt="avatar" className="img-fluid rounded-circle" style={{ width: 36 }} /> </NavLink> </NavItem> <NavItem className="d-flex align-items-center"> <NavLink className="font-weight-bold" href="/">Home</NavLink> </NavItem> <NavItem className="d-flex align-items-center"> <NavLink className="font-weight-bold" href="/">Events</NavLink> </NavItem> <UncontrolledDropdown className="d-flex align-items-center" nav inNavbar> <DropdownToggle className="font-weight-bold" nav caret>Learn</DropdownToggle> <DropdownMenu end> <DropdownItem className="font-weight-bold text-secondary text-uppercase" header disabled>Learn React</DropdownItem> <DropdownItem divider /> <DropdownItem>Documentation</DropdownItem> <DropdownItem>Tutorials</DropdownItem> <DropdownItem>Courses</DropdownItem> </DropdownMenu> </UncontrolledDropdown> </Nav> </Col> <Col className="d-flex justify-content-xs-start justify-content-lg-center"> <NavbarBrand className="d-inline-block p-0" href="/" style={{ width: 80 }}> <img src={logo} alt="logo" className="position-relative img-fluid" /> </NavbarBrand> </Col> <Col className="d-none d-lg-flex justify-content-end"> <Form inline> <Input type="search" className="mr-3" placeholder="Search React Courses" /> <Button type="submit" color="info" outline>Search</Button> </Form> </Col> </Row> </Container> </Navbar> </header> ); export default Header;
The component we just created in the snippet above is the Header
component, which contains the navigation menu. Next, we will create a new file named SideCard.js
— also in the components
directory — with the following contents:
import { Button, UncontrolledAlert, Card, CardImg, CardBody, CardTitle, CardSubtitle, CardText } from "reactstrap"; const BANNER = "https://i.imgur.com/CaKdFMq.jpg"; const SideCard = () => ( <> <UncontrolledAlert color="danger" className="d-none d-lg-block"> <strong>Account not activated.</strong> </UncontrolledAlert> <Card> <CardImg top width="100%" src={BANNER} alt="banner" /> <CardBody> <CardTitle className="h3 mb-2 pt-2 font-weight-bold text-secondary"> Glad Chinda </CardTitle> <CardSubtitle className="text-secondary mb-3 font-weight-light text-uppercase" style={{ fontSize: "0.8rem" }} > Web Developer, Lagos </CardSubtitle> <CardText className="text-secondary mb-4" style={{ fontSize: "0.75rem" }} > Full-stack web developer learning new hacks one day at a time. Web technology enthusiast. Hacking stuffs @theflutterwave. </CardText> <Button color="success" className="font-weight-bold"> View Profile </Button> </CardBody> </Card> </> ); export default SideCard;
Once that’s done, create a file named Post.js
in the components
directory and add the following code snippet to it:
import { useState, useEffect } from "react"; import axios from "axios"; import { Badge } from "reactstrap"; const Post = () => { const [post, setPost] = useState(null); useEffect(() => { axios .get( "https://baconipsum.com/api/?type=meat-and-filler¶s=4&format=text" ) .then((response) => setPost(response.data)); }, []); return ( <> {post && ( <div className="position-relative"> <span className="d-block pb-2 mb-0 h6 text-uppercase text-info font-weight-bold"> Editor's Pick <Badge pill color="success" className="text-uppercase px-2 py-1 ml-3 mb-1 align-middle" style={{ fontSize: "0.75rem" }} > New </Badge> </span> <span className="d-block pb-4 h2 text-dark border-bottom border-gray"> Getting Started with React </span> <article className="pt-5 text-secondary text-justify" style={{ fontSize: "0.9rem", whiteSpace: "pre-line" }} > {post} </article> </div> )} </> ); }; export default Post;
In the code above, we created a Post
component that renders a post on the page. We initialized the component’s state by setting the post property to null
.
After the component was mounted, we used the useEffect
Hook and Axios to retrieve a random post of four paragraphs from the Bacon Ipsum JSON API, and changed our post field to the data returned from this API.
Finally, modify the src/App.js
file to look like the following snippet:
import { Container, Row, Col } from "reactstrap"; import Post from "./components/Post"; import Header from "./components/Header"; import SideCard from "./components/SideCard"; const App = () => ( <> <Header /> <main className="my-5 py-5"> <Container className="px-0"> <Row g-0 className="pt-2 pt-md-5 w-100 px-4 px-xl-0 position-relative" > <Col xs={{ order: 2 }} md={{ size: 4, order: 1 }} tag="aside" className="pb-5 mb-5 pb-md-0 mb-md-0 mx-auto mx-md-0" > <SideCard /> </Col> <Col xs={{ order: 1 }} md={{ size: 7, offset: 1 }} tag="section" className="py-5 mb-5 py-md-0 mb-md-0" > <Post /> </Col> </Row> </Container> </main> </> ); export default App;
In the code above, we simply included the Header
, SideCard
, and Post
components in the App
component. Notice how we used a couple of responsive utility classes provided by Bootstrap to adapt our app to different screen sizes.
If you run the app now with the command yarn start
or npm
run dev
, your app should start on port 5173
and look like this:
One of the most notable drawbacks of using Bootstrap is that every app created with it tends to look the same. However, Bootstrap provides the option of customizing the appearance and feel of our app by overriding its default style and creating custom styling using a preprocessor like Sass.
Bootstrap provides access to a number of Sass variables that define its default styling attributes, such as colors, typography, spacing, and more. These variables can be overridden or customized to create a unique look and feel for our application. For example, we can change the primary color and font like this:
$primary-color: #007bff; // Change the primary color to blue $font-family-sans-serif: 'Helvetica Neue', Arial, sans-serif; // Change the default font
To get started with Sass, install the compiler with the following command:
npm install -g sass
The Bootstrap team advises against modifying the core files, so we need to create a custom Sass stylesheet that imports Bootstrap. Therefore, the next step is to create a custom.scss
file in the root directory of our project and import Bootstrap’s source files:
// Scss/custom.scss // Include all of Bootstrap @import "../node_modules/bootstrap/scss/bootstrap"; // Then add additional custom code here ...
The Bootstrap file we are importing resides within the /node_modules/bootstrap
directory, which is the directory housing the core Bootstrap files. Within this directory, you’ll find three subfolders: dist
, js
, and scss
.
The dist
folder contains all the compiled Sass files in CSS format, the js
folder contains all of Bootstrap’s JavaScript files, and the scss
file contains the Sass files with the default styles.
Bootstrap also offers the option of importing only the required Sass source files into our custom stylesheet, as opposed to importing the whole of Bootstrap:
// Scss/custom.scss // Include function @import "../node_modules/bootstrap/scss/functions"; // Include variables and mixins @import "../node_modules/bootstrap/scss/variables"; @import "../node_modules/bootstrap/scss/mixins";
The only distinction between the two methods above is that with the first method, i.e., importing the entirety of Bootstrap, functions will not be accessible. We’ll learn more about this later in this section.
After creating the custom scss
file, your project’s file structure should look like the following:
├── scss │ └── custom.scss └── node_modules/ └── bootstrap ├── js └── scss
With the setup in place, we can now begin modifying our Bootstrap styles. But first, we need to understand how Bootstrap styles are arranged and how to define custom variables.
Bootstrap allows users to override Sass properties such as variables, functions, maps, etc. However, there is a specific order that must be followed when modifying these properties in a custom Sass file.
For example, custom variables must be defined before the import statements in the file, except for the function import statement, which must be defined before, or above, declared custom variables. So, if we were to put the example from earlier into our custom.scss
file, it would be arranged as follows:
// Scss/custom.scss // Include functions @import "../node_modules/bootstrap/scss/functions"; // Custom variables $primary-color: #007bff; $success: #ff0000; $font-family-sans-serif: 'Helvetica Neue', Arial, sans-serif; // Import variables @import "../node_modules/bootstrap/scss/variables";
If we were to use the method of importing the entirety of the Bootstrap utilities, we would not be able to modify functions in our custom file. This is because the imported file will overwrite the functions.
Every Sass variable in Bootstrap is prefixed with a !default
flag, which allows us to override the value without modifying the source code. The example above changes the theme’s primary color and font. The list of Bootstrap’s variables can be found in the \node_modules\bootstrap\scss_variables.scss
directory of your project. Edit the variables accordingly to change the theme’s appearance.
In addition to overriding variables, we can also write custom styles to further modify the appearance of specific elements or components using Sass maps. With maps, we can write custom styles such as the following and merge them with an existing map:
// Create a custom map $custom-colors: ( "custom-color": #900 ); // Merge the maps $theme-colors: map-merge($theme-colors, $custom-colors);
Here, we’re using the map-merge
method to merge our custom map with the existing $theme-colors
map. To see our custom styles in action, we must first compile the custom.scss
file and replace the Bootstrap CSS we imported into main.jsx
earlier with the compiled output file.
This is the command for compiling our Sass file:
sass ./scss/custom.scss ./src/css/custom.css
This command will compile the output CSS file into a CSS folder within the src
directory in your project:
Next, replace the Bootstrap CSS import inside the main.js
file with the compiled custom.css
file like so:
// Bootstrap CSS import "./css/custom.css"; // Bootstrap Bundle JS import "bootstrap/dist/js/bootstrap.bundle.min";
We didn’t use the progress
variable anywhere in our application. The success
variable, however, is used to define the color of both the button
and badge
components on the page. If you return to your web browser, you will see that they have now taken on the red color specified in our custom Sass file:
With this knowledge, you can tailor your application’s design to your liking without any limitations. Please refer to the documentation for more information on Bootstrap customization with Sass.
In the previous section, we employed a set of utility classes to adapt our app to different screen sizes. These utility classes are parts of the Bootstrap grid system, which is a utility that allows us to create responsive and adaptable layouts. It is based on a 12-column flexbox grid, which can be customized to create layouts of varying complexity:
Bootstrap uses a series of containers
, rows
, and columns
elements that work together to align content on different screen sizes.
container
In Bootstrap, the container
element is essential for grid layouts because it houses other grid elements. Bootstrap offers two containers: container
with a fixed, centered width for standard layouts, and container-fluid
for full-width layouts.
row
The row
element, used within the container
element, forms horizontal containers for columns, ensuring proper alignment and equal height.
column
The column
element is the primary building block of the grid system. It is placed inside rows and defines how much horizontal space each item occupies. The columns are designated by the col-
class, which is followed by a number from one to 12. For example, col-6
will create a column that spans half the width of its parent row:
Bootstrap also provides responsive breakpoint classes that allow you to control the layout of columns at different screen sizes. These classes are typically applied alongside the col-
classes:
col-sm-
: Applies to small screens, with a minimum width of 576pxcol-md-
: Applies to medium screens, with a minimum width of 768pxcol-lg-
: Applies to large screens, with a minimum width of 992pxcol-xl-
: Applies to extra-large screens, with a minimum width of 1200pxHere’s a simple example of a Bootstrap grid layout:
<div class="container"> <div class="row"> <div class="col-md-4">Column 1</div> <div class="col-md-4">Column 2</div> <div class="col-md-4">Column 3</div> </div> </div>
In this example, we have a container that holds a row with three columns. On medium sized screens and larger, each column occupies four out of 12 available columns, creating a three column layout:
Alternatively, Bootstrap offers an auto-layout feature that enables users to create responsive layouts without specifying the exact widths of columns. In an auto-layout, columns with a col
class will automatically size themselves to be equal width within the same row. This means that if you have three columns with col
classes inside a row, each will take up an equal portion of the available width:
<div class="container"> <div class="row"> <div class="col">Column 1</div> <div class="col">Column 2</div> <div class="col">Column 3</div> </div> </div>
In this example, the output reflects the previous one: all three columns are of equal width, each occupying one-third of the row:
Upon closer inspection, you’ll notice that we used a slightly different syntax when creating our columns. This is because the col
element in React is a component from the React-Bootstrap library that receives its responsive classes as props:
<Container className="px-0"> <Row g-0 className="pt-2 pt-md-5 w-100 px-4 px-xl-0 position-relative" > <Col xs={{ order: 2 }} md={{ size: 4, order: 1 }} tag="aside" className="pb-5 mb-5 pb-md-0 mb-md-0 mx-auto mx-md-0" > <SideCard /> </Col> <Col xs={{ order: 1 }} md={{ size: 7, offset: 1 }} tag="section" className="py-5 mb-5 py-md-0 mb-md-0" > <Post /> </Col> </Row> </Container>
In this example, we used the Container
, Row
, and Col
components from the React-Bootstrap library to structure our grid. We also specified the column widths using the xs
(extra small) and md
(medium) props.
There are 12 columns in this grid, and each column takes up 4
and 7
columns on medium sized screens, respectively:
On extra small screens, each column spans the entire row, but with an ordering of 2
and 1
, respectively. This means that the first column appears after the second column on extra small screens, and the second one appears before the first.
Finally, this is how our responsive grid layout will look on different screens:
In this tutorial, we explored a few different ways in which we can integrate Bootstrap with our React apps. We also learned how to use two of the most popular React Bootstrap libraries, React-Bootstrap and Reactstrap, to build responsive layouts and streamline the development process.
We have only used a few Bootstrap components in this tutorial, including alerts, badges, dropdowns, navbars, navs, forms, buttons, and cards. There are still a few Bootstrap components you can experiment with, such as tables, modals, tooltips, carousel, jumbotron, pagination, and more.
Check out the documentation of the packages we used in this tutorial to find out more ways they can be used. The source code for all the demo apps in this tutorial can be found on GitHub.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowLearn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
Handle frontend data discrepancies with eventual consistency using WebSockets, Docker Compose, and practical code examples.
Efficient initializing is crucial to smooth-running websites. One way to optimize that process is through lazy initialization in Rust 1.80.
9 Replies to "Using Bootstrap with React: Tutorial with examples"
Awesome!
Great article upon react + bootstrap combination!
Great! Thanks for this post.
Nice post! Just a comment: MenuItem has been changed to DropdownItem
Nice post!
thanksss!!!!
Hi, you shouldn’t include any CDN scripts to public/index.html, it ruins all the reactivity.
Use react-bootstrap instead with CDN styles. This is the best approach.
Thanks, I really appreciate. I want to know if it’s possible to use react and flask
1. Looking at CDN example, where’s the reference to external CSS and JS?
2. ThemeSwitcher.js has multiple reference to class attributes!
very good