Masatoshi Nishiguchi
Software Engineer

React Font Awesome regular and solid icons

react fontawesome icon

For example, if a like button has the heart icon, I want to toggle it between the regular and solid based on the like status.

Install react-fontawesome

# Install the library core.
$ yarn add @fortawesome/react-fontawesome
$ yarn add @fortawesome/fontawesome-svg-core
# Install necessary icons.
$ yarn add @fortawesome/free-solid-svg-icons
$ yarn add @fortawesome/free-regular-svg-icons

Find icons

Find icon constant names for JS use

React

Import the FontAwesomeIcon component

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

Import icon

import { faHeart as faHeartActive } from '@fortawesome/free-solid-svg-icons';
import { faHeart as faHeartInactive } from '@fortawesome/free-regular-svg-icons';

If there is no naming collision, it is simple.

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faGithub } from '@fortawesome/free-brands-svg-icons';
<FontAwesomeIcon icon={faGithub} />;

Example component

import React from 'react';
import { Card, CardText, CardBody, CardTitle } from 'reactstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHeart as faHeartActive } from '@fortawesome/free-solid-svg-icons';
import { faHeart as faHeartInactive } from '@fortawesome/free-regular-svg-icons';

const likeIcon = (liked) => (liked ? faHeartActive : faHeartInactive);

const ExampleLikeableCard = ({
  name,
  explanation,
  liked,
  likeCount,
  className = '',
}) => {
  const iconStyle = { color: liked ? 'red' : 'inherit' };
  return (
    <Card className={className}>
      <CardBody>
        <CardTitle>{name}</CardTitle>
        <CardText>{explanation}</CardText>

        <Button outline>
          <FontAwesomeIcon
            icon={likeIcon(liked)}
            fixedWidth={true}
            style={iconStyle}
          />
          <span className="ml-1">{likeCount}</span>
        </Button>
      </CardBody>
    </Card>
  );
};

export default ExampleLikeableCard;

That’s it.