I want to check for a true value on a state and set a class accordingly. The code below does just this, However...
Is there a way to do this programmatically, maybe through a for loop to add all of the inline function checks.
The reason for this is because there are instances where I have hundreds of items, and I would hate to repeat and paste the same code hundreds of times.
class App extends React.Component {
constructor() {
super();
this.state = {
item1: false,
item2: true,
item3: false
}
}
render() {
return(
<div className="app">
<ul>
<li data-item="item1" className={(this.state.item1) ? "active" : null}>Item 1</li>
<li data-item="item2" className={(this.state.item2) ? "active" : null}>Item 2</li>
<li data-item="item3" className={(this.state.item3) ? "active" : null}>Item 3</li>
</ul>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
.active {
color: green;
}
<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>
<div id="app"></div>
this.state = { items: [item1,item2,item3]....}