2

How to handle toggle class onclick function in mapping list dom.

this.state.data.map(function(el,i){
    var className = self.state.condition ? 'list-row active' : 'inactive';
    return <div className={className} key={i} onClick={self.handleClick.bind(self)}>
            <div>List</div>
        </div>
    });
1
  • Could you please elaborate your question a bit more? Maybe show the complete component and write what you need exactly. Commented Feb 17, 2017 at 14:24

2 Answers 2

1

Move the whole div and onClick handler to another component, and just map that component with props from the array. Something like:

const ChildComponent = ({ condition, handleClick }) => {
  var className = condition ? 'list-row active' : 'inactive';
  return (
    <div className={className} onClick={() => handleClick()}>
      <div>List</div>
    </div>
  )
}

and just use this component in the container:

this.state.data.map((el ,i) => (
  <ChildComponent key={i} condition={this.state.condition} handleClick={() => this.handleClick()} />
))

I am not sure if you want your child to also have state, but that is easily achievable too, using the same practice. I strongly suggest using ES6 syntax for react (arrow functions, etc.), makes life so much easier without having to keep track of tthis/self and binding it everywhere.

Sign up to request clarification or add additional context in comments.

Comments

0

If you only want to keep 1 item active, you can keep a reference to the selected item in your state. Then you can write an onClick callback to change the selected item.

var MyList = React.createClass({
  getInitialState: function(){
    return {
      data: ['foo', 'bar', 'baz'],
      selected: null
    }
  },

  selectItem: function(el){
    this.setState({selected: el});
  },

  renderItem: function(el){
    var className = this.state.selected === el ? 'active' : 'inactive';
    var onClick = this.selectItem.bind(this, el);
    return <li key={el} className={className} onClick={onClick}>{el}</li>;
  },

  render: function() {
    return (
      <ul>
      { this.state.data.map(this.renderItem) }
      </ul>
     );
  }
});

ReactDOM.render(
  <MyList />,
  document.getElementById('container')
);

If you want to be able to toggle between active and inactive on each list item, you can use the same approach but keep an object as your selected state:

getInitialState: function(){
    return {
      data: ['foo', 'bar', 'baz'],
      selected: {}
    }
  },

  selectItem: function(el){
    var selected = this.state.selected;
    selected[el] = !selected[el];
    this.setState({selected: selected});
  },

And modify your renderItem function accordingly:

var className = this.state.selected[el] ? 'active' : 'inactive';
var onClick = this.selectItem.bind(this, el);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.