Skip to content

Font Awesome Icons with Pseudo-Elements

Font Awesome's fifth iteration is huge with the company finally moving to SVG icons from their flagship icon fonts.

With this change, the company has also published packages like react-fontawesome and @fortawesome/fontawesome-svg-core.

This is great for the consumer, because we no longer have to ship the complete icon font. SVG imports with Package managers like Webpack and Parcel ensure that only the icons we use are present in the bundle.

But lots of earlier code would depend on pseudo elements, sort off like this:

<button class="button">Thing</button>
.button {
  width: 100%;
  padding-left: 4rem;
}
.button::before {
  content: "\f7e5";
  font-family: "Font-Awesome";
}

For comparison, here is how you render an SVG icon when rendering with React FontAwesome library and SVG Core:

const element = <FontAwesomeIcon icon={faCoffee} />;

ReactDOM.render(element, document.body);

So, how do we migrate the psuedo element code to the React one? There is no easy answer to that and it involves some markup changes.

First, we have to introduce the icon into the markup.

function App() {
  return (
    <button className="button">
      <FontAwesomeIcon icon={faCoffee} className="icon" />
      <span className="button-text">Text</span>
    </button>
  );
}

ReactDOM.render(<App />, document.body);

Now, you can change the css to:

.button {
  width: 100%;
  padding-left: 4rem;
}
.icon {
  // whatever styles you want the color to take.
  color: red;
}

There could be more complicated cases, refer to this PR on BuffetJS to see more cases.

Bonus: How does the SVG change color when you apply color to it's parent class?

If you inspect the fontawesome SVGs, you will find their path elements have an attribute in common:

<path fill="currentColor" ...></path>

Read more on the trick at CSS Tricks


Stay ahead of the curve in Web Development with Javascript Every Month Newsletter.

I will deliver a curated selection of articles, tutorials, and resources straight to your inbox once a month.

Read the Archives

Subscribe to JEM Newsletter

No spam, unsubscribe anytime.