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

React Bootstrap tutorial

15 min read 4375

How To Use Bootstrap With React

How to use Bootstrap with React

With the increasing popularity of single-page applications over the last few years, so many frontend JavaScript frameworks have emerged, such as Angular, React, Vue.js, Ember — the list goes on. As a result, using DOM libraries such as jQuery is no longer a necessary requirement for building web apps.

On the other hand, a couple of CSS frameworks also emerged to help meet the requirements of building responsive web apps. Almost every frontend developer must have either used or heard about Bootstrap, Foundation, or Bulma, each being a responsive (mobile-first) CSS framework with robust features and built-in utilities.

While React has become the most-used JavaScript framework for building web applications, Bootstrap is the most popular CSS framework, powering millions of websites on the internet. So it becomes necessary to explore various ways in which Bootstrap can be used in React apps, and that is the aim of this tutorial.

This tutorial does not in any way attempt to teach either React or Bootstrap in detail; it is expected that you already have some prior experience working with React and/or Bootstrap. If you need help with any of these, check the React docs and the Bootstrap documentation.

Add Bootstrap for React

Bootstrap can be added to your React app in several ways. In this tutorial, we are only interested in the three most common ways:

  1. Using the Bootstrap CDN
  2. Bootstrap as dependency
  3. React Bootstrap package

Using the Bootstrap CDN

This is the easiest way to add Bootstrap to your app. No installs or downloads required. You simply put a <link> into the <head> section of your app as shown in the following snippet.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" 
integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" 
crossorigin="anonymous">

If you are interested in using the JavaScript components that ship with Bootstrap, you need to place the following <script> tags near the end of your pages, right before the closing </body> tag, to enable them.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" 
integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" 
crossorigin="anonymous"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" 
integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" 
crossorigin="anonymous"></script>

As you can see, Bootstrap 4 requires jQuery and Popper.js for its JavaScript components. In the above snippet, we used jQuery’s slim version, although you can use the full version as well.

For your React app, these code snippets will usually be added to the index page of your app. If you used create-react-app to create your app, then your public/index.html page should look like the following snippet:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" 
    integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" 
    crossorigin="anonymous">
    
    <title>React App</title>
  </head>
  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.
      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.
      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
    
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
    crossorigin="anonymous"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" 
    integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" 
    crossorigin="anonymous"></script>
    
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" 
    integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" 
    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 as a dependency

If you are using a build tool or a module bundler such as webpack, then this is the preferred option for adding Bootstrap to your React application. You will need to install Bootstrap as a dependency for your app.

npm install bootstrap

Or if you are using Yarn:

yarn add bootstrap

Once you have Bootstrap installed, you will go ahead to include it to your app’s entry JavaScript file. If you are used to create-react-app, this should be your src/index.js file.

import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

Notice that we have imported the Bootstrap minified CSS as the first dependency. With this, we can go ahead using the built-in Bootstrap classes in our React app components. However, before you can use Bootstrap’s JavaScript components in your app, you’ll need to install jquery and popper.js if they are not already installed.

npm install jquery popper.js

Next, you will make additional changes to the src/index.js file to add the new dependencies as shown in the following snippet.

import 'bootstrap/dist/css/bootstrap.min.css';
import $ from 'jquery';
import Popper from 'popper.js';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Dropdown />, document.getElementById('root'));
registerServiceWorker();

Here we added imports for $ and Popper. We also imported the Bootstrap JavaScript minified bundle file. Now you can use Bootstrap JavaScript components in your React app.

React Bootstrap package

The third way we can add Bootstrap to our React app is by using a package that has rebuilt Bootstrap components to work particularly as React components. There are a couple of such packages available in the npm repository, but I will emphasize the two most popular of them in this tutorial, namely:

  1. react-bootstrap
  2. reactstrap

Both packages are great choices for using Bootstrap with React apps although you are not necessarily required to use any of them. They share very similar characteristics.

Using built-in Bootstrap classes and components

You can use Bootstrap directly on elements and components in your React app by applying the built-in classes just like any other class. Let’s build a simple theme switcher React component to demonstrate using Bootstrap classes and components.

Theme Switcher Demo

As shown in this demo, we are using a dropdown component available in Bootstrap to implement our theme switcher. We also use the built-in button classes to set the size and color of the dropdown button.

We will go ahead to write the code for our ThemeSwitcher component. Ensure you have a React application already set up. Create a new file for the component and add the following code snippet to it:

import React, { Component } from 'react';

class ThemeSwitcher extends Component {

  state = { theme: null }
  
  resetTheme = evt => {
    evt.preventDefault();
    this.setState({ theme: null });
  }
  
  chooseTheme = (theme, evt) => {
    evt.preventDefault();
    this.setState({ theme });
  }
  
  render() {
  
    const { theme } = this.state;
    const themeClass = theme ? theme.toLowerCase() : 'secondary';
    
    return (
      <div className="d-flex flex-wrap justify-content-center position-absolute w-100 h-100 align-items-center align-content-center">
      
        <span className={`h1 mb-4 w-100 text-center text-${themeClass}`}>{ theme || 'Default' }</span>
        
        <div className="btn-group">
        
          <button type="button" className={`btn btn-${themeClass} btn-lg`}>{ theme || 'Choose' } Theme</button>
          
          <button type="button" className={`btn btn-${themeClass} btn-lg dropdown-toggle dropdown-toggle-split`} data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <span className="sr-only">Toggle Theme Dropdown</span>
          </button>
          
          <div className="dropdown-menu">
          
            <a className="dropdown-item" href="#" onClick={e => this.chooseTheme('Primary', e)}>Primary Theme</a>
            <a className="dropdown-item" href="#" onClick={e => this.chooseTheme('Danger', e)}>Danger Theme</a>
            <a class="dropdown-item" href="#" onClick={e => this.chooseTheme('Success', e)}>Success Theme</a>
            
            <div className="dropdown-divider"></div>
            
            <a className="dropdown-item" href="#" onClick={this.resetTheme}>Default Theme</a>
          </div>
          
        </div>
        
      </div>
    );
    
  }
  
}

export default ThemeSwitcher;

Here we have built a very simple theme switcher component leveraging on Bootstrap’s dropdown component and a couple of built-in classes. You can learn more about using Bootstrap dropdown here.

First, we set up the component’s state with a theme property and initialized it to null. Next, we defined two click event handlers resetTheme() and chooseTheme() on the component class for choosing a theme and resetting the theme respectively.

In the render() method, we render a split button dropdown menu containing three themes. namely: Primary, Danger, and Success. Each menu item is attached to a click event handler for the appropriate action. Notice how we use theme.toLowerCase() to get the theme color class for both the dropdown buttons and the text. We default to using secondary as the theme color if no theme is set.

In this example, we have seen how easy it is to use Bootstrap’s built-in classes and components in our React app. Check the Bootstrap documentation to learn more about the built-in classes and components.

Using react-bootstrap

Now, we will rebuild our theme switcher using react-bootstrap. We will use the create-react-app command-line tool to create our app. Ensure that you have the create-react-app tool installed on your machine.

Create a new React app using create-react-app as follows:

create-react-app react-bootstrap-app

Next, go ahead and install the dependencies as follows:

yarn add bootstrap@3 react-bootstrap

react-bootstrap currently targets Bootstrap v3. However, work is actively ongoing to provide Bootstrap v4 support.

Create a new file named ThemeSwitcher.js in the src directory of your project and put the following content in it.

import React, { Component } from 'react';
import { SplitButton, MenuItem } from 'react-bootstrap';

class ThemeSwitcher extends Component {

  state = { theme: null }
  
  chooseTheme = (theme, evt) => {
    evt.preventDefault();
    if (theme.toLowerCase() === 'reset') { theme = null }
    this.setState({ theme });
  }
  
  render() {
  
    const { theme } = this.state;
    const themeClass = theme ? theme.toLowerCase() : 'default';
    
    const parentContainerStyles = {
      position: 'absolute',
      height: '100%',
      width: '100%',
      display: 'table'
    };
    
    const subContainerStyles = {
      position: 'relative',
      height: '100%',
      width: '100%',
      display: 'table-cell',
      verticalAlign: 'middle'
    };
    
    return (
      <div style={parentContainerStyles}>
        <div style={subContainerStyles}>
        
          <span className={`h1 center-block text-center text-${theme ? themeClass : 'muted'}`} style={{ marginBottom: 25 }}>{theme || 'Default'}</span>
          
          <div className="center-block text-center">
            <SplitButton bsSize="large" bsStyle={themeClass} title={`${theme || 'Default'} Theme`}>
              <MenuItem eventKey="Primary" onSelect={this.chooseTheme}>Primary Theme</MenuItem>
              <MenuItem eventKey="Danger" onSelect={this.chooseTheme}>Danger Theme</MenuItem>
              <MenuItem eventKey="Success" onSelect={this.chooseTheme}>Success Theme</MenuItem>
              <MenuItem divider />
              <MenuItem eventKey="Reset" onSelect={this.chooseTheme}>Default Theme</MenuItem>
            </SplitButton>
          </div>
          
        </div>
      </div>
    );
    
  }
  
}

export default ThemeSwitcher;

Here we have tried to mimic our initial example as much as possible using react-bootstrap. We import two components from the react-bootstrap package, namely SplitButton and MenuItem. See the react-bootstrap Dropdown documentation to learn more.

First, we set up the component’s state with a theme property and initialized it to null. Next, we define a chooseTheme() click event handler for choosing a theme or resetting the theme.

Since we are using Bootstrap 3.3.7, we created some container styles in the render() method to help us achieve horizontal and vertical centering.

Notice how we specify the button size on the SplitButton component using the bsSize prop. Also, notice how we are passing the themeClass to the bsStyle prop to dynamically change the button color based on the state’s theme.

We pass the theme name to the eventKey prop of each MenuItem component. We also set the onSelect handler to this.chooseTheme(), which we defined earlier. The MenuItem component passes the eventKey and the event itself to the onSelect handler as follows:

(eventKey: any, event: Object) => any

Finally, we will modify the src/index.js file to look like the following snippet:

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/css/bootstrap-theme.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ThemeSwitcher from './ThemeSwitcher';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<ThemeSwitcher />, document.getElementById('root'));
registerServiceWorker();

Here, we first import Bootstrap’s minified CSS files. We also import our ThemeSwitcher component and render it to the DOM.

If you run the app now with the command yarn start or npm start. Your app should start on port 3000 and should look like the following demo:

react-bootstrap demo.

Using reactstrap

We will go ahead and rebuild our theme switcher using reactstrap this time. We will use the create-react-app command-line tool to create our app. Ensure that you have the create-react-app tool installed on your machine.

Create a new React app using create-react-app as follows:

create-react-app reactstrap-app

Next, go ahead and install the dependencies as follows:

yarn add bootstrap reactstra

Create a new file named ThemeSwitcher.js in the src directory of your project and put the following content in it:

import React, { Component } from 'react';
import { Button, ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';

class ThemeSwitcher extends Component {

  state = { theme: null, dropdownOpen: false }
  
  toggleDropdown = () => {
    this.setState({ dropdownOpen: !this.state.dropdownOpen });
  }
  
  resetTheme = evt => {
    evt.preventDefault();
    this.setState({ theme: null });
  }
  
  chooseTheme = (theme, evt) => {
    evt.preventDefault();
    this.setState({ theme });
  }
  
  render() {
  
    const { theme, dropdownOpen } = this.state;
    const themeClass = theme ? theme.toLowerCase() : 'secondary';
    
    return (
      <div className="d-flex flex-wrap justify-content-center position-absolute w-100 h-100 align-items-center align-content-center">
      
        <span className={`h1 mb-4 w-100 text-center text-${themeClass}`}>{theme || 'Default'}</span>
        
        <ButtonDropdown isOpen={dropdownOpen} toggle={this.toggleDropdown}>
          <Button id="caret" color={themeClass}>{theme || 'Custom'} Theme</Button>
          <DropdownToggle caret size="lg" color={themeClass} />
          <DropdownMenu>
            <DropdownItem onClick={e => this.chooseTheme('Primary', e)}>Primary Theme</DropdownItem>
            <DropdownItem onClick={e => this.chooseTheme('Danger', e)}>Danger Theme</DropdownItem>
            <DropdownItem onClick={e => this.chooseTheme('Success', e)}>Success Theme</DropdownItem>
            <DropdownItem divider />
            <DropdownItem onClick={this.resetTheme}>Default Theme</DropdownItem>
          </DropdownMenu>
        </ButtonDropdown>
        
      </div>
    );
    
  }
  
}

export default ThemeSwitcher;

Here we have rebuilt our initial example using reactstrap. We import a couple of components from reactstrap. See the reactstrap Button Dropdown documentation to learn more.

First, we set up the component’s state with two properties:

  1. theme property initialized to null
  2. dropdownOpen initialized to false. This property will be used in the ButtonDropdown component from reactstrap to maintain the toggle state of the dropdown.

We also define a toggleDropdown() method to toggle the open state of the dropdown. This will also be used in the ButtonDropdown component.
reactstrap also provides an uncontrolled component UncontrolledButtonDropdown that does not require the isOpen prop or the toggle handler prop to work. In most cases, this can be used instead of using ButtonDropdown.

Each item in the dropdown menu is rendered using the DropdownItem component. Notice how we specify the button size on the DropdownToggle component using the size prop. Also notice how we are passing the themeClass to the color prop on both the Button and DropdownToggle components to dynamically change the button color based on the state’s theme.

We also set the onClick handler on each DropdownItem just like we did before, using the chooseTheme() and resetTheme() handlers we defined earlier.

Finally, we will modify the src/index.js file to look like the following snippet:

import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ThemeSwitcher from './ThemeSwitcher';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<ThemeSwitcher />, document.getElementById('root'));
registerServiceWorker();

Here, we first import the Bootstrap minified CSS file. We also import our ThemeSwitcher component and render it to the DOM.

If you run the app now with the command yarn start or npm start. Your app should start on port 3000 and should look like the following demo:

reactstrap Demo

Create a 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 much Bootstrap classes and components as possible. We will also use reactstrap for integrating Bootstrap with React, since it supports Bootstrap 4.

We will use the create-react-app command-line tool to create our app. Ensure that you have the create-react-app tool installed on your machine. Here is a screenshot of what we will be creating.

App Screenshot

Create a new React app using create-react-app as follows:

create-react-app sample-app

Next, go ahead and install the dependencies as follows:

yarn add axios bootstrap reactstrap

Notice here that we install 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 BaconIpsum JSON API.

Make a little modification to the src/index.js file to include the Bootstrap minified CSS file. It should look like the following snippet:

import 'bootstrap/dist/css/bootstrap.min.css';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

Create a new directory named components in the src directory of your project. Create a new file, Header.js, in the just-created components directory with the following content:

import React from 'react';
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 this snippet is the Header component that contains the navigation menu. Next, we will create a new file named SideCard.js in the components directory with the following content:

import React, { Fragment } from 'react';

import {
  Button, UncontrolledAlert, Card, CardImg, CardBody,
  CardTitle, CardSubtitle, CardText
} from 'reactstrap';

const BANNER = 'https://i.imgur.com/CaKdFMq.jpg';

const SideCard = () => (
  <Fragment>
  
    <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>
    
  </Fragment>
);

export default SideCard;

Next, create a new file named Post.js in the components directory and add the following code snippet to it:

import React, { Component, Fragment } from 'react';
import axios from 'axios';
import { Badge } from 'reactstrap';

class Post extends Component {

  state = { post: null }
  
  componentDidMount() {
    axios.get('https://baconipsum.com/api/?type=meat-and-filler&paras=4&format=text')
      .then(response => this.setState({ post: response.data }));
  }
  
  render() {
    return (
      <Fragment>
        { this.state.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' }}>{this.state.post}</article>
          
        </div> }
      </Fragment>
    );
  }
  
}

export default Post;

Here we created a Post component that renders a post on the page. We initialize the state of the component with a post property set to null. When the component mounts, we use axios to fetch a random post of four paragraphs from the BaconIpsum JSON API and update the post property in the state.

Finally, modify the src/App.js file to look like the following snippet:

import React, { Fragment } from 'react';
import axios from 'axios';
import { Container, Row, Col } from 'reactstrap';

import Post from './components/Post';
import Header from './components/Header';
import SideCard from './components/SideCard';

const App = () => (
  <Fragment>
  
    <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>
    
  </Fragment>
);

export default App;

Here we simply include the Header, SideCard, and Post components in the App component. Notice how we use 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.

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.


Plug: LogRocket, a DVR for web apps

LogRocket Dashboard Free Trial Banner

 is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

.

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

One Reply to “React Bootstrap tutorial”

Leave a Reply