React Bootstrap Badge class not rendering

Viewed 866

i'm new to react devolopment, i'm testing a simple react web app where i use bootstarp

i installed bootstrap latest version with npm and i added the import in my index.js like so

import "bootstrap/dist/css/bootstrap.min.css";

and this is my component

class Counter extends Component {
  state = {
    count: 0,
  };
  render() {
    return (
      <React.Fragment>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button className="btn btn-secondary">Increment</button>
      </React.Fragment>
    );
  }

  getBadgeClasses() {
    let classes = "badge m2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : count;
  }
}

export default Counter;

now the button class is rendering correctly but the badge class is not.

i'm i missing something here ?

2 Answers

In the latest versions (5.x) of Bootstrap one needs set contextual badges using bg-* rather than badge-* as stated here.

You therefore, need the following:

getBadgeClasses() {
    let classes = "badge m2 bg-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

you need to bind the functions:

constructor(props) {
    super(props);
    this.state = {count: 0};

    // This binding is necessary to make `this` work in the callback
    this.getBadgeClasses= this.getBadgeClasses.bind(this);
    this.formatCount= this.formatCount.bind(this);
  }
Related