Glad Chinda Full-stack web developer learning new hacks one day at a time. Web technology enthusiast. Hacking stuffs @theflutterwave.

Using Bootstrap with React: Tutorial with examples

13 min read 3735

Editor’s note: This post was updated on 23 June 2022 to ensure all information is current and add a section about how to troubleshoot Bootstrap not working in React.

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 is 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’ll go over:

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 tutorial below for a deeper dive.

Brief introduction to JavaScript and CSS frameworks

There are many JavaScript frameworks you could choose from, including Angular, React, Vue.js, Ember — the list goes on. Thanks to these plentiful 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 already mentioned, React and Bootstrap are currently the most popular JavaScript and CSS frameworks, respectively. Next, let’s go over how to add Bootstrap to React.

How to add Bootstrap to React

The three most common ways to add Bootstrap to your React app are:

  • Using the Bootstrap CDN
  • Importing Bootstrap in React as a dependency
  • Installing a React Bootstrap package such as react-bootstrap or reactstrap

Let’s go over each of these in more detail.

Add Bootstrap to React using Bootstrap CDN

The Bootstrap CDN is the easiest way to add Bootstrap to your React app. No extra installation or download is required.

You’ll only have to include a link to the CDN in the head section of your application entry file. In a typical React application created with create-react-app, that would be in the public/index.html file.

Since we’ll want to include the current stable version of Bootstrap, our link would look like this:

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

If your project would also require 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 the </body> tag:

<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>

After linking the Bootstrap CSS and bundled Javascript CDNs, the complete code for our public/index.html file would 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.

Import Bootstrap in React as a dependency

If you are using a build tool or a module bundler such as webpack, this would be the preferred option for adding Bootstrap to your React application. You can easily start the installation by running the below:

npm install bootstrap
# OR
yarn add bootstrap

This command will install the most recent version of Bootstrap. Once the installation is completed, 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 create-react-app, that would be in the src/index.js file. The entire file’s content would look like this after the import:

import React from "react";
import ReactDOM from "react-dom/client";

// Bootstrap CSS
import "bootstrap/dist/css/bootstrap.min.css";
// Bootstrap Bundle JS
import "bootstrap/dist/js/bootstrap.bundle.min";

import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

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 completed, we can go ahead and start using the built-in Bootstrap classes in our React app components.

Install a React Bootstrap package such as react-bootstrap or reactstrap

The third way to add Bootstrap to a React app is to use a package that has rebuilt 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 could now be easily imported as <Modal /> in our React application.

While there are various packages you can use to install Boostrap in React, the two most popular include react-bootstrap and reactstrap. Both packages are great choices for using Bootstrap with React apps and share very similar characteristics.

Using built-in Bootstrap classes and components

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.



Theme Switcher Demo Using Built-In Bootstrap Classes And Components Showing Dropdown Button With Three Colored Themes And One Default Theme

As shown in this demo, we are using a dropdown component 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.

We will go ahead and write the code for our theme switcher component. Ensure you have a React application 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 couple of built-in classes.

Using React’s useState hook, we’ve created a state theme and set its initial value to null, as well as defined the setTheme method to modify this state. Then we also created a resetTheme function, that resets the theme’s value to null.

Next, in our component markup, we’ve 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 have seen how easy it is to use Bootstrap’s built-in classes and components in our React app. To further understand how the React Bootstrap packages work as well, let’s recreate our theme switcher application using the components provided by react-bootstrap and reactstrap while writing limited code.

Example using react-bootstrap

Assuming that you already have a React application set up, let’s install react-bootstrap in our application with the command below:

npm install react-bootstrap bootstrap

It’s worth mentioning that react-bootstrap doesn’t come pre-installed with Bootstrap itself; i.e., its CSS and JavaScript files. The package only exports common Bootstrap 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 content 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 have 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 utilized 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 snippet:

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 create-react-app starter page and making it render our ThemeSwitcher component instead.

If we run the app now with the command yarn start or npm start, our app should start on port 3000 and should look like the following demo:

Theme Switcher Demo Using react-bootstrap Showing Dropdown Button With Three Colored Themes And One Default Theme

Example using reactstrap

The reactstrap package is quite similar to react-bootstrap, with minor differences in things such as component and prop names. However, 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 would 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 reactsrap 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 should look like the following demo:

Theme Switcher Demo Using reactstrap Showing Dropdown Button With Three Colored Themes And One Default Theme

Create a more detailed React app with Bootstrap

Let’s push this a bit further to create an app with some more details. We will try to use as many Bootstrap classes and components as possible. We will also use reactstrap to add Bootstrap to React. Here’s what our final result will look like:

Screenshot Of More Detailed React App Built Using reactstrap Showing Menu Bar, Profile And Image On Left, And Article On Right

Let’s get started by creating a new app with create-react-app:

npx create-react-app sample-app

Next, go ahead and install the dependencies as follows:

npm install axios bootstrap reactstrap

Notice here 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";
// Bootstrap CSS
import "bootstrap/dist/css/bootstrap.min.css";
// Bootstrap Bundle JS
import "bootstrap/dist/js/bootstrap.bundle.min";

import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
reportWebVitals();

Next, we’ll crease a new directory named components inside the src directory of our project. In this new components directory, create a new file called Header.js and update it with the following content:

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 noGutters 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 right>
                  <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 content:

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 new 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&paras=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 utilized the useEffect hook and Axios to retrieve a random post of four paragraphs from the Bacon Ipsum JSON API and change 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
          noGutters
          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 start, your app should start on port 3000 and should look exactly like the screenshot we saw earlier.

How to troubleshoot Bootstrap not working in React

The only reason Bootstrap might not operate properly in your React application is if you haven’t properly linked it.

If you’re using the Bootstrap CDN, double-check that the CDN URL is valid and that it’s added using the <link /> tag in the head section of your application entry page.

If you’re using a React Bootstrap package, make sure you’ve installed it correctly and imported it on your application entry page, as we covered earlier.

Conclusion

In this tutorial, we explored a few different ways in which we can integrate Bootstrap with our React apps. We have also seen how we can use two of the most popular React Bootstrap libraries, namely react-bootstrap and reactstrap.

We have only used a few Bootstrap components in this tutorial, such as alert, badge, dropdown, navbar, nav, form, button, card, etc. There is still a couple of Bootstrap components you can experiment with, such as tables, modals, tooltips, carousel, jumbotron, pagination, tabs, etc.

You can check 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.

Cut through the noise of traditional React error reporting with LogRocket

LogRocket is a React analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your React applications. LogRocket automatically aggregates client side errors, React error boundaries, Redux state, slow component load times, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to notify you of the most impactful problems affecting the most users and provides the context you need to fix it.

Focus on the React bugs that matter — .

Glad Chinda Full-stack web developer learning new hacks one day at a time. Web technology enthusiast. Hacking stuffs @theflutterwave.

7 Replies to “Using Bootstrap with React: Tutorial with examples”

  1. 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.

  2. Thanks, I really appreciate. I want to know if it’s possible to use react and flask

Leave a Reply