Here I have given example in ES6.  When the state of component changes, then ReactJS will re render the component. By using this concept, we can manipulate classes on the go

classnames npm package 

install classnames npm package. Here is the syntax
npm install classnames --save

To Run Example Code

execute below commands
npm install
npm start
now open index.html in browser

Example Component 

Observe below component. Whenever user clicks on buttons, respective class manipulation actions will happen. Here redTextClass will be added and removed based on redText state variable 
import React from 'react'
import classNames from 'classnames'

class ExampleApplication extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
       redText: false
    };
    this.addClass = this.addClass.bind(this);
    this.removeClass = this.removeClass.bind(this);
    this.verifyClass = this.verifyClass.bind(this);
  }

  addClass() {
    this.setState({
      redText:true
    });
  }

  removeClass() {
    this.setState({
      redText:false
    });
  }

  verifyClass() {
    alert(this.state.redText);
  }

  render() {
    return (
      <div>
        <p className={classNames("boldTextClass", {"redTextClass":this.state.redText})}>some text here</p>
        <button onClick={this.addClass}>add class</button>
        <button onClick={this.removeClass}>remove class</button>
        <button onClick={this.verifyClass}>verify class</button>
      </div>
    );
  }

}

ExampleApplication.propTypes = {
}

ExampleApplication.defaultProps = {
}

export default ExampleApplication;

0 comments:

Blogroll

Follow this blog by Email

Popular Posts