Font Awesome 5 was recently released and it comes with a lot of really great changes. The coolest thing is now it supports "svg with js". This basically means that instead of acting like a font, Font Awesome will now convert your html tags into inline SVGs.
Cool. Wait, why is this cool? Maybe some day we can go into all the cool things we can do with inline SVGs, but the tl;dr is it gives us more control over our icons and we no longer have to include every single icon into our project. We can just load the ones we're going to use.
Luckily, we've all moved over to using Stimulus instead of that "J word", it's actually really easy to start using Font Awesome 5 in our Rails app.
Before we get started, we're going to assume your project already has:
First thing we need to do is, well, install Font Awesome. To do that, we'll need to install a few yarn packages.
yarn add @fortawesome/fontawesome yarn add @fortawesome/fontawesome-free-regular yarn add @fortawesome/fontawesome-free-brands
The Stimulus Controller
Great, now we have Font Awesome installed in our project. It's time to actually start using it. To do that, we'll make a new Stimulus controller in
icons_controller.js. The purpose of the controller will be to:
- Initialize all of the icons we need access to in our app.
- Hook Turbolinks and Font Awesome together so icons will be rendered properly.
Here's the code for our controller:
Boom. So the first thing we did is tell Font Awesome which icons we want to use in the
initialize() method of our controller. This code is only run once when the controller is setup. Then, in the
connect() method we can tell Font Awesome to search for any
<i class="far fa-*"></i> tags and convert them into inline SVGs. Using the
connect() method tells Stimulus to run this check every time the controller gets added to the dom, whether that be the initial page load, or pages loaded by Turbolinks.
Now that we have our sweet new icons controller, it's time for us to add it to our app so it can start doing its job. Since we want our icons to work throughout our app, the best place to add the controller is in our layout on the
<body> tag. Really all we have to do is just add
data-controller="icons" to the
<body> tag and we're done. Your layout should look something like this:
// views/layouts/application.html.erb <html> <head></head> <body data-controller="icons"> ... </body> </html>
If you have multiple layout files, you'll want to make sure you add this to each of them.
That's it! Now you can access any icons you want by adding
<i class="far fa-icon-name"></i> in your app. For a complete list of all the icons you can add, check out the gallery. Hope this helps!