DEV Community

Vorachith Kip
Vorachith Kip

Posted on • Updated on

Rails 6 with BootStrap 5

To make a Rails 6 project with a responsive design as fast as possible, Bootstrap can be a nice solution. The flexibility and the compatibility with any browser allow you to deliver a consistent design quickly.

How To add Bootstrap to a Ruby on Rails Application

Unlike on Rails 5, Rails 6 doesn't require to add jQuery and Popper.js gems in the Gemfiles to make BootStrap works. Below the stack that i use in this tutorial, note that you can't use Rails 6 with the latest node version.

Rails 6.0.4
ruby 2.6.5
node v14.17.1
yarn 1.22.10
Enter fullscreen mode Exit fullscreen mode

Build your Ruby on Rails application

I - Create the rails project

To begin, let's create the rails 6 project in the console.

rails new rails-n-bootstrap && cd rails-n-bootstrap 
Enter fullscreen mode Exit fullscreen mode

It will take less than 1 minute to building the project, be sure to launch 'bundle install' after that.

II - Adding a Controller, the Homepage page and define routes

Let's explain what we will do now. We have to build a page to ensure BootStrap works. For this, 3 steps:

  • create a controller "Pages" with a "homepage" page
  • add some bootstrap code in the homepage;
  • define routes
  • run the server

To create the home controller, you can use the rails generate command with the controller generator. In this case, we will specify that we want an index view for our main landing page:

1 - Creating the controller with a landing page
We will use the rails generate command to create the controller and add the homepage page.

rails g controller Pages homepage
Enter fullscreen mode Exit fullscreen mode

2 - Adding some bootstrap code in the homepage page
We will add some BootStrap code in the homepage that you can access by app/views/pages/homepage.html.erb. Copy/paste the code below so you don't need to worry about the BootStrap syntax for the moment.

<div class="container mt-4 border">
  <div class="container-content">
    <h1 class="m-3">Rails 6 with Bootstrap 🚀🚀🚀</h1>
    <div class="m-3">
    <p class="">Quick demonstration of bootstrap on a rails web application.</p>
    <h2>Features</h2></h2>
      <span>
        <ul>
          <li>Create the rails 6 project</li>
          <li>Add Bootstrap</li>
          <li>Add navbar component</li>
          <li>Add homepage page</li>
        </ul>
      </span>
    </div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

3 - Define routes
We have to configure a default route in config/routes.rb

Rails.application.routes.draw do
  get 'pages/homepage'
  root to: "pages#homepage"
end
Enter fullscreen mode Exit fullscreen mode

4 - Create a navbar component
We will build a component after creating the folder.

mkdir app/views/shared
Enter fullscreen mode Exit fullscreen mode
touch app/views/shared/_navbar.html.erb
Enter fullscreen mode Exit fullscreen mode

in this file, we add the html code

<div class="gradient-custom border">
  <ul class="nav justify-content-center">
    <li class="nav-item">
      <a class="nav-link active" aria-current="page" href="http://localhost:3000">Homepage</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="https://getbootstrap.com/docs/5.1/getting-started/introduction/" target="_blank">Bootstrap doc</a>
    </li>
    <li class="nav-item">
      <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
    </li>
    <li class="nav-item">
      <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
    </li>
  </ul>
</div>
Enter fullscreen mode Exit fullscreen mode

Don't forget to make a render of this component in the application layout at the top inside the body app/views/layouts/application.html.erb

<%= render 'shared/navbar' %>
Enter fullscreen mode Exit fullscreen mode

6 - Run the server
To check the homepage, just launch the below command and open localhost:3000 to your browser.

rails s
Enter fullscreen mode Exit fullscreen mode

As you can see, no design is showing. Don't panic, it's normal we didn't add bootstrap yet.

Using BootStrap 5 with Rails

I - Add BootStrap

1 - Add bootstrap and required dependencies
Like i told you in the introduction, BootStrap needs to be installed with required dependencies (jquery and popper.js). We have to add it by yarn.

yarn add bootstrap jquery popper.js
Enter fullscreen mode Exit fullscreen mode

2 - Adding the Webpack library with a ProvidePlugin
Essential, we define the ProvidePlugin so Bootstrap can interpret Popper and JQuery.
So we replace the main webpack configuration file, config/webpack/environment.js with your editor. I personally use Visual Studio Code, but not a problem if you use another one.

const { environment } = require('@rails/webpacker')

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)

module.exports = environment

Enter fullscreen mode Exit fullscreen mode

3 - Import Bootstrap in the webpack entry point file
Next, we import bootstrap in application.js file in app/javascript/packs/application.js

import 'bootstrap'; 
Enter fullscreen mode Exit fullscreen mode

4 - Allow the using of Sass with Bootstrap
We will use Sass in the project so we can add some variables into our Style Sheets. For this step, nothing very complicated, just change the file extension of app/assets/stylesheets/application.css to app/assets/stylesheets/application.scss and add some code.

// Graphical variables
@import "config/fonts";
@import "config/colors";
@import "config/bootstrap_variables";

// External libraries
@import "bootstrap/scss/bootstrap";
Enter fullscreen mode Exit fullscreen mode

II - Organize your Bootstrap structure

In the last step, we imported some file who didn't exist yet. We will create those files in assets/stylesheets/config and add some code inside.

touch app/assets/stylesheets/config/_bootstrap_variables.scss
touch app/assets/stylesheets/config/_colors.scss
touch app/assets/stylesheets/config/_fonts.scss
Enter fullscreen mode Exit fullscreen mode

1 - _bootstrap_variables.scss

// General style
$font-family-sans-serif:  $body-font;
$headings-font-family:    $headers-font;
$body-bg:                 $light-gray;
$font-size-base: 1rem;

// Colors
$body-color: $gray;
$primary:    $blue;
$success:    $green;
$info:       $yellow;
$danger:     $red;
$warning:    $orange;

// Buttons & inputs' radius
$border-radius:    2px;
$border-radius-lg: 2px;
$border-radius-sm: 2px;

// Other variables
Enter fullscreen mode Exit fullscreen mode

2 - _colors.scss

$red: #FD1015;
$blue: #167FFB;
$yellow: #FFC65A;
$orange: #E67E22;
$green: #1EDD88;
$gray: #0E0000;
$light-gray: #F4F4F4;
Enter fullscreen mode Exit fullscreen mode

3 - _fonts.scss

// Import the Google fonts that you choose
@import url('https://fonts.googleapis.com/css?family=Nunito:400,700|Work+Sans:400,700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Russo+One&display=swap');

// Define fonts 
$body-font: "Work Sans", "Helvetica", "sans-serif";
$headers-font: "Nunito", "Helvetica", "sans-serif";
Enter fullscreen mode Exit fullscreen mode

III - Add a components folder

Any web application has components that can be used later.
In app/assets/stylesheets/application.scss, we will add a components import.

...
// CSS partials
@import "components/index";
Enter fullscreen mode Exit fullscreen mode

1 - After that, we create the components folder

mkdir app/assets/stylesheets/components
Enter fullscreen mode Exit fullscreen mode

2 - Next, we create the index that will contain all the components imports

touch app/assets/stylesheets/components/_index.scss
Enter fullscreen mode Exit fullscreen mode

3 - Add the below code in _index.scss

@import "navbar";
Enter fullscreen mode Exit fullscreen mode

4 - The navbar import isn't create yet, so we build it. The file can be used for custom css, we add it so you can see how to organize your project.

touch app/assets/stylesheets/components/_navbar.scss
Enter fullscreen mode Exit fullscreen mode

5 - Add some style in _navbar.scss

  .gradient-custom {
    background: #f0f0f0;
    background: -webkit-linear-gradient(to bottom, rgba(240, 240, 240, 0.5), rgba(211, 217, 227, 0.5));
    background: linear-gradient(to bottom, rgba(240, 240, 240, 0.5), rgba(211, 217, 227, 0.5))
  }
Enter fullscreen mode Exit fullscreen mode

V - Final change

Let's make some change in the views/layouts/application.html.erb

<meta name="viewport" content="width=device-width, initial-scale=1">
    <title>rails-n-bootstrap</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload', defer: true %>

Enter fullscreen mode Exit fullscreen mode

Before to conclude, some explanations.

<meta name="viewport" content="width=device-width, initial-scale=1">
Enter fullscreen mode Exit fullscreen mode

This part of code manage is added for the responsive behaviors.

To conclude

You can now manage the building of a Rails application with Bootstrap.

To know more about Bootstrap, you can check the official documentation. https://getbootstrap.com/docs/5.1/getting-started/introduction/

If you need to read the rails 6 doc, just see the next link.
https://guides.rubyonrails.org/v6.0/

Discussion (0)