Add Bootstrap 5 to Rails 6
Updated on 2022-08-22
I was following an online course and came up with an issue caused by the difference in bootstrap versions between the one I was using and the one the instructor was using. I'm sure the easiest way to fix it was to install the right version, but I was taking the course to learn something and I wanted to set some desirable difficulties for best results, so I gave myself a challenge.
After doing some online research and looking through many forums I finally found something that worked for me.
The Issue
This is a rails application, which uses gems. Therefore my thought process was to just install the Bootstrap gem version of my choice and expect it to work. It didn't. I did manage to make the CSS part work and make the website look decent, but I couldn't get the menu dropdown to work, which relied on JavaScript.
Here's What You Need
Important: This was managed with the following versions:
ruby 2.7.6
rails 6.1.6.1
@popperjs/core ^2.11.6
bootstrap 5.0.0
node 12.22.12
1. Install what you need
First of all, you don't need any gems. Just install bootstrap 5 and popper.js with the following:
yarn add @popperjs/core bootstrap@5.0.0
.
I'm sure you could use npm instead.
But wait! what's @popperjs/core
? Where did that come from? Well, for Bootstrap's JavaScript, you need popper.js because Bootstrap relies on it for positioning popovers. It's a dependency. You should end up with the screenshot below.
2. Add code
Next, add *= require bootstrap
in application.css like below.
And another line in application.js to use popper.js like the image below.
Import bootstrap in application.jsGreat! Now you're ready to use Bootstrap with Rails 6.
3. A possible next step
In some cases, you may want to override the default styling from Bootstrap. The next section will talk about this and will assume you've done the yarn add
the two packages, as well as, the versions used are the same.
Override Bootstrap Styles
This will show you one way to override bootstrap styles without relying on !important
.
- Add
gem 'bootstrap', '~> 5.0.0'
to Gemfile, thenbundle install
- Remove
*= require bootstrap
from assets/stylesheets/application.css, which we added originally. This should have removed bootstrap styles if you check your app. - Create an scss file in the same directory like so assets/stylesheets/custom.css.scss. You can name this file anything except application and bootstrap, otherwise, it'll cause a Sprockets::DoubleLinkError and SassC::SyntaxError, respectively.
- Finally, add this line
@import "bootstrap";
to the scss file, and check your app to see bootstrap styles return. Now you should be able to override bootstrap styles in the file without using!important
.