Classnames is a simple yet versatile javascript utility that joins CSS class names based on a set of conditions. We are going to build a simple toggle switch that relies on state to determine what CSS classes will be applied.

//className = require('classnames')
const className = window.classNames; class ClassnamesExample extends React.Component { constructor(props) {
super(props);
this.state = {
isOn: false
};
} toggleState = () => { this.setState({isOn: !this.state.isOn}); } render() { const circleClasses = className({
circle: true,
off: !this.state.isOn,
on: this.state.isOn
}); const textClasses = className({
textOff: !this.state.isOn
}) console.log(circleClasses);
// <div className="circle off"></div>
// <span className="textOff">{this.state.isOn ? 'ON' : 'OFF' }</span>
return (
<div onClick={this.toggleState}> <div className={circleClasses}></div>
<span className={textClasses}>{this.state.isOn ? 'ON' : 'OFF' }</span>
</div>
);
}
} window.onload = () => { ReactDOM.render(<ClassnamesExample/>, document.getElementById('app')); }

to JsBin

05-02 15:38