Toggling Font Awesome 5 icon with React
The font-awesome javascript doesn't rerender on a React rerender trigger. 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-fontawesomeyarn add @fortawesome/fontawesome-free-regular @fortawesome/fontawesome-free-solid
Example 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
This answer is an edited version of my answer here: How can I get Font Awesome 5 to work with React?.
Since FA 5 injects svg elements into the DOM, it probably doesn't play nicely with React's virtual DOM. Hopefully it's something they'll fix, but a simple workaround is to just include both icons instead of toggling them, and hide one or the other by wrapping it in a container that applies display: none
. For example:
renderChatButton() { const unread = this.state.unread const normalIcon = <i className='far fa-comment' /> const unreadIcon = <i className='fas fa-comment' /> return ( <div className='header-button' onClick={ this.toggleChat }> <span className={ unread ? 'hidden' : '' }>{ normalIcon }</span> <span className={ unread ? '' : 'hidden' }>{ unreadIcon }</span> </div> )}
Looks like another fix is to call window.FontAwesomeConfig = { autoReplaceSvg: 'nest' }
somewhere in your app's boot cycle, after the FA JavaScript has been loaded.
See also https://stackoverflow.com/a/48552226/53790 and https://fontawesome.com/how-to-use/svg-with-js#auto-replace-svg-nest.