Rails 6 with BootStrap 5 
Tags: ruby, rails, bootstrap
Published: 2021-08-14 13:11:52

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. 

<h2>How To add Bootstrap to a Ruby on Rails Application</h2>

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


<h3>Build your Ruby on Rails application</h3>

<h4>I - Create the rails project</h4>

To begin, let's create the rails 6 project in the console.
```
rails new rails-n-bootstrap && cd rails-n-bootstrap 
```
It will take less than 1 minute to building the project, be sure to launch 'bundle install' after that.


<h4>II - Adding a Controller, the Homepage page and define routes</h4>

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

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.
```ruby
<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>
```

3 - Define routes 
We have to configure a default route in config/routes.rb
```ruby
Rails.application.routes.draw do
  get 'pages/homepage'
  root to: "pages#homepage"
end
```

4 - Create a navbar component
We will build a component after creating the folder.
```
mkdir app/views/shared
```
```
touch app/views/shared/_navbar.html.erb
```
in this file, we add the html code
```html
<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>
```
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
```ruby
<%= render 'shared/navbar' %>
```

6 - Run the server
To check the homepage, just launch the below command and open localhost:3000 to your browser.
```
rails s
``` 
As you can see, no design is showing. Don't panic, it's normal we didn't add bootstrap yet.

<h3>Using BootStrap 5 with Rails</h3>

<h4>I - Add BootStrap</h4>
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
```

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. 
```js
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

```

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'; 
```

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.
```scss
// Graphical variables
@import "config/fonts";
@import "config/colors";
@import "config/bootstrap_variables";

// External libraries
@import "bootstrap/scss/bootstrap";
```

<h4>II - Organize your Bootstrap structure</h4>
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
```

1 - _bootstrap_variables.scss
```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
```

2 - _colors.scss
```scss
$red: #FD1015;
$blue: #167FFB;
$yellow: #FFC65A;
$orange: #E67E22;
$green: #1EDD88;
$gray: #0E0000;
$light-gray: #F4F4F4;
```

3 - _fonts.scss
```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";
```

<h4>III - Add a components folder</h4>
Any web application has components that can be used later. 
In app/assets/stylesheets/application.scss, we will add a components import. 
```scss
...
// CSS partials
@import "components/index";
```
1 - After that, we create the components folder
```
mkdir app/assets/stylesheets/components
```
2 - Next, we create the index that will contain all the components imports
```
touch app/assets/stylesheets/components/_index.scss
```
3 - Add the below code in _index.scss
```
@import "navbar";
```
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
```
5 - Add some style in _navbar.scss 
```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))
  }
```

<h4>V - Final change</h4>
Let's make some change in the views/layouts/application.html.erb
```html
<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 %>

```

Before to conclude, some explanations.
```html
<meta name="viewport" content="width=device-width, initial-scale=1">
```
This part of code manage is added for the responsive behaviors.

<h3>To conclude</h3>
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/