guillaumek guillaumek - 1 month ago 11
React JSX Question

react - create an active class when onClick on child

i'm using Meteor/ReactJS and i'm building a TodoList with lists. When a user click on a list item, I display the tasks associated to this list.
I can get the items, I'm calling the onClick with a parent function.
The problem is I would like to add an "active" class to the list item I just clicked. But I don't know how to do it on the parent class or neither in the child..

Here is the parent class (i'm calling this function in the render():

selectList(listId) {
this.setState({ listSelected: listId });
}

renderLists() {
return this.props.lists.map((list) => (
<List
selectList={() => this.selectList(list._id)}
key={list._id}
list={list}
/>
));
}


and here is the child:

render() {
return (
<ListGroupItem onClick={this.props.selectList}>
{this.props.list.name}
<span className="pushRight">
<Glyphicon
onClick={() => this.deleteThisList()}
glyph="glyphicon glyphicon-remove"
/>
</span>
</ListGroupItem>
);
}


How could I get the result of selectList in parent and then give the class to the child, or How could I handle the click in the child and give the class directly in the child ?

Thanks a lot for help :)

Answer

Parent

1.pass selected id to List comp

selectList(listId) {
    this.setState({ listSelected: listId });
}

renderLists() {
    return this.props.lists.map(list => (
        <List
          selectedItemId={this.state.listSelected}
          selectList={() => this.selectList(list._id)}
          key={list._id}
          list={list}
        />
    ));
}

Child

2.Compare list.id with passed selectedItemId, if true, so this item is active

render() {
  const { selectList, list, selectedItemId} = this.props;
    return (
        <ListGroupItem isActive={list.id==selectedItemId} onClick={selectList}>
          {list.name}
          <span className="pushRight">
            <Glyphicon
              onClick={() => this.deleteThisList()}
              glyph="glyphicon glyphicon-remove"
                />
          </span>
        </ListGroupItem>
    );
}

3.then in ListGroupItem

  render(){
      const {isActive}=this.props;
        return (
          <div className={"someclass "+(isActive? 'active':'')}>
            .......
          </div>
        );
    }