Search code examples
reactjsclassdynamicclass-names

Set class dynamically using classNames module not working


thanks in advance for taking a look at this. I am attempting to set the class on page load of my element to pending, and then onClick, remove the pending class and add the completed class:

Currently, the state of completed and pending change accordingly; however, the classes do not change (pending is still active class and completed is not active). Any help would be greatly appreciated!

import React, { Component } from 'react';
import classNames from 'classnames';
import '../stylesheets/Task.css';

class Task extends Component {
  constructor(props) {
    super(props);

    this.state = {
      completed: false,
      pending: true
    }

    this.makeComplete = this.makeComplete.bind(this);
  }

  makeComplete() {
    if (this.state.pending) {
      this.setState({
        completed: true,
        pending: false
      }, () => {
        console.log('completed: ' + this.state.completed, '\npending: ' + this.state.pending);
      });
    }
  }

  render() {
    return (
      <div className="task">
        <div className="check-task-container" onClick={this.makeComplete} >
          <i className={classNames({
            completed: this.state.completed,
            pending: this.state.pending,
            far: true,
            'fa-circle': true
        })} ></i>
        </div>
        {this.props.title}
      </div>
    );
  }
}

Solution

  • This issue was really related to the fontawesome conversion of the i element to an svg as React was unaware of the change in the element when rendering. To solve the issue, I had to use the fontawesome node module (https://www.npmjs.com/package/@fortawesome/react-fontawesome) instead of using the fontawesome CDN.