flyfisher1952
flyfisher1952

Reputation: 432

How to display FontAwesome icons in react HTML set with dangerouslySetInnerHTML

I have a react.js web app and a REST API that returns a chunk of raw HTML (not a complete page). I get the HTML by scrapping a website and grabbing a piece of the markup using cherrio.js. In the developer tools, the response itself is the markup. I use the dangerouslySetInnerHTML={{ __html: htmlMarkup }} element attribute so that react knows to display it as the inner HTML.

However, I need to insert some FontAwesome icons into it. I've tried both straight HTML using, <i class="fa-solid fa-star-sharp"></i>, and the react version, <FontAwesomeIcon icon="fa-solid fa-star-sharp" />. Both of these come straight from the FA docs.

Within my component that inserts the HTML I import the FontAwesomeIcon component (import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";) and also import the FontAwesome CDN CSS file using a SASS file that I import into my root JS file. I also import the @fortawesome/fontawesome-svg-core/styles.css file.

SASS file: fa.scss @import url(https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/fontawesome.min.css);

index.js import 'fa.scss';

However, after I load the HTML markup, insert my icon, and then set the dangerouslySetInnerHTML attribute, my icon doesn't display.

What am I missing?

Upvotes: 0

Views: 371

Answers (1)

flyfisher1952
flyfisher1952

Reputation: 432

I fixed this by using react-icons. I cheated by adding the icon I wanted to a regular page, inspecting the HTML element in Chrome dev tools, and copying the SVG that react-icons generates for the icon into a string in my code. I then replace the icon used in the markup with the SVG markup.

Works like a charm.

There is also a way to programmatically add the required FontAwesome CSS file into the markup as a react element which also worked. But once I saw that react-icons had everything I needed and is free, I switched over.

Upvotes: 0

Related Questions