You're close, you just put the className
part outside:
<span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter.bind(this,'completed')}>Completed</span>
Off-topic side note:
Using bind
in the onClick
every time means you'll re-bind every time that element is rendered. You might consider doing it once, in the component's constructor:
class YourComponent extends React.Component {
constructor(...args) {
super(...args);
this.handleFilter = this.handleFilter.bind(this);
// ...
}
handleFilter() {
// ...
}
render() {
return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
}
}
Another option is to make it an arrow function, if you've enabled class properties in your transpiler (they're in the stage-2
preset in Babel as of this writing, January 2017):
class YourComponent extends React.Component {
// ...
handleFilter = event => {
// ...
};
render() {
return <span className={this.state.visibilityFilter=="completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
}
}
Live example of that one:
class YourComponent extends React.Component {
constructor() {
super();
this.state = {
visibilityFilter: ""
};
}
handleFilter = event => {
this.setState({
visibilityFilter: "completed"
});
};
render() {
return <span className={this.state.visibilityFilter == "completed" ? "active" : ""} onClick={this.handleFilter}>Completed</span>;
}
}
ReactDOM.render(
<YourComponent />,
document.getElementById("react")
);
.active {
color: blue;
}
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>