Search code examples
javascriptreactjsfont-awesomefont-awesome-5

Font awesome 5: icon not switching when condition changes


I'm using font awesome 5 in a react.js project, and having trouble make the icon switch in a conditional statement. Here's the sample code:

!isRecording
&&
<div style={styles.recordButton} onClick={e => this.record(e)}>
    <span className="fa-layers  fa-4x">
      <div><i className="fas fa-circle " style={{color: Colors.mainOrange}}></i></div>
      <div><i className="fa fa-microphone  fa-inverse" data-fa-transform="shrink-6"></i></div>
    </span>
</div>
||
<div style={styles.recordButton} onClick={e => this.stop(e)}>
    <span className="fa-layers  fa-4x">
      <div><i className="fas fa-circle " style={{color: Colors.mainOrange}}></i></div>
      <div><i className="fas fa-stop  fa-inverse" data-fa-transform="shrink-6"></i></div>
    </span>
</div>

When isRecording == true, the icon should change from fa-microphone to fa-stop. But the switch doesn't happen. The microphone icon stays.

Strangely, when I don't use the fa-layers class in the button to be switched in, the switch happens. But the transition is super awkward--icon size and position shift:

!isRecording
&&
<div style={styles.recordButton} onClick={e => this.record(e)}>
    <span className="fa-layers  fa-4x">
      <div><i className="fas fa-circle " style={{color: Colors.mainOrange}}></i></div>
      <div><i className={isRecording ? `fa fa-stop  fa-inverse` : `fa fa-microphone  fa-inverse`} data-fa-transform="shrink-6"></i></div>
    </span>
</div>
||
<div style={styles.recordButton} onClick={e => this.stop(e)}>
    <span className=" fa-2x">
      <div key="stopRecord"><i className="fa fa-stop-circle fa-2x" style={{color: Colors.mainOrange}}></i></div>
    </span>
</div>

Any idea why this is happening?


Solution

  • I've experimented around with your code and realized that you are using FontAwesome's new SVG JavaScript library which completely explains the problem. The code that that library uses to look at the DOM and insert the icons doesn't play well with React. This is also discussed here.

    To solve this problem, you can either ...