Search code examples
javascriptreactjsfont-awesomefont-awesome-5

How can I get Font Awesome 5 to work with React?


In the following example, the initial icon renders but it does not change when the class changes.

const Circle = ({ filled, onClick }) => {
  const className = filled ? 'fas fa-circle' : 'far fa-circle';
  
  return (
    <div onClick={onClick} >
      <i className={className} />
      <p>(class is {className})</p>
    </div>
  );
};

class App extends React.Component {
  state = { filled: false };

  handleClick = () => {
    this.setState({ filled: !this.state.filled });
  };
  
  render() {
    return <Circle filled={this.state.filled} onClick={this.handleClick} />;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>


Solution

  • BO41 is right, it is the font-awesome javascript that doesn't rerender. If you are okay with not using the new font-awesome svg/javascript icons, you can use font-awesome as a webfont with css.

    In your index.html, delete the fontawesome script, and add the font-awesome css stylesheet:

    <link href="https://use.fontawesome.com/releases/v5.0.2/css/all.css" rel="stylesheet">
    

    Your code should work now.


    The other possibility is to use the official font-awesome react package (it's a bit more of a hassle, but it uses the new svg icons)

    Add necessary packages to project:

    yarn add @fortawesome/fontawesome @fortawesome/react-fontawesome
    yarn add @fortawesome/fontawesome-free-regular @fortawesome/fontawesome-free-solid
    

    And the updated code:

    import fontawesome from '@fortawesome/fontawesome'
    import FontAwesomeIcon from '@fortawesome/react-fontawesome'
    import { faCircle as fasCircle } from '@fortawesome/fontawesome-free-solid'
    import { faCircle as farCircle } from '@fortawesome/fontawesome-free-regular'
    
    const Circle = ({ filled, onClick }) => {
    
      return (
        <div onClick={onClick} >
          <FontAwesomeIcon icon={filled ? farCircle : fasCircle}/>
        </div>
      );
    };
    
    class App extends React.Component {
      state = { filled: false };
    
      handleClick = () => {
        this.setState({ filled: !this.state.filled });
      };
    
      render() {
        return <Circle filled={this.state.filled} onClick={this.handleClick} />;
      }
    }
    

    See the github repo for more information: https://github.com/FortAwesome/react-fontawesome