phantom phantom - 10 months ago 64
React JSX Question

Add className to li item react

I am trying to update the active class when a user clicks on a button. Each time this button is clicked on the next item should have the class name

added and removed from the previous one. Using jQuery I could use the
methods. Something along these lines would get me started.

$("button").click(function() {
$("ul li").removeClass("active");
var length = $(this).prevAll().length;
$("ul li:eq(" + length + ")").addClass("active");

I am not sure how I should go about implementing this using react.

I have set up a JSFIDDLE here.

var App = React.createClass({

getInitialState: function(){

return {
active: 0

incrementIndex: function() {
this.setState({active : + 1});

render: function () {
<ArtistList active={} />
<Button increment={this.incrementIndex} />


var ArtistList = React.createClass({

render: function() {

<li className="active">Michael Jackson</li>
<li>Bob Dylan</li>
<li>Kendrick Lamar</li>


var Button = React.createClass({
render: function() {
<button onClick={this.props.increment}>next</button>

Answer Source

You can generate the list elements dynamically by iterating over an array containing the list content. Then you can simply compare the passed prop with the current iteration:

var data = ['Michael Jackson', 'Bob Dylan', 'Kendrick Lama'];
var listItems =, index) => (
    className={ === index ? 'active' : ''}>

return <ul>{listItems}</ul>;