The Complete React on Rails 5 Course

You're viewing a lesson from an old course. Click here to get access to the new version.

Using Bootstrap with React

In this tutorial we look at how to use Bootstrap with React

This video was part of the The Complete React on Rails 5 Course.

A new version of the course is now available

Enrol now to view this video

Lesson code -

In this lesson we’ll look at using Bootstrap with React.

In addition to the CSS library, we'll also use react-bootstrap.  This is a React library that provide bootstrap elements as React components.

So let's install the libraries first:

npm i react-bootstrap --save
and let's install bootstrap 3

npm i [email protected] --save
Now let’s use it for adding a navbar header,  Let’s open up AppHeader and lets import the bootstrap css files.  (AppHeader.js lines 1-5):

import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import $ from 'jquery';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
And you can see immediately the font has changed. Now let’s replace our code in the header here with some bootstrap components.

Let’s import some of these components from react bootstrap. (AppHeader.js lines 1-6):

import React from 'react';
import { Link, Redirect } from 'react-router-dom';
import $ from 'jquery';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import { Grid, Navbar, Nav, NavItem } from 'react-bootstrap';
And then I’m going to replace lines 39- 45 with a navbar.  (AppHeader.js lines 35-57):

render () {
  if(sessionStorage.getItem('user')) {
    return (
        <Navbar inverse fixedTop>
                <Link to='/'>
              <Navbar.Toggle />
              <Nav pullRight>
                <NavItem eventKey={2} href="#" onClick={this.handleSignOut}>Sign out</NavItem>

We have a dark fixed top navbar. So we still have the same content - the name of the app with a link to the homepage, the current user’s email address and the sign out link.

Only they're now inside this  Bootstrap components structure.

Ok let's see how this looks.

Ok, so we have the title on the left and a collapsed menu on the right.

And it’s responsive. If I widen the window, the email and sign out links appear.

Only our page sub title has got hidden behind the navbar.

So let’s fix that by adding a bit of top margin to the body in our index.css file. (index.css lines lines 1-8):

body {            
  margin:100px auto;            
  font-family: Arial, sans-serif;            
  font-size: 14px;            
  line-height: 1.5;            
  padding-bottom: 200px;            
Ok, so this is how to use bootstrap in a React app.

The react_on_rails gem also has built in support for bootstrap, so you can also use it directly there if you're not using it in a standalone react app.

Liked this tutorial? Get more like this in your inbox