Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  13] [ 7]  / answers: 1 / hits: 27750  / 8 Years ago, tue, august 23, 2016, 12:00:00

So basically what I am doing is iterating through an array of data and making some kind of list. What I want to achieve here is on clicking on a particular list item a css class should get attached.



Iteration to make a list



var sports = allSports.sportList.map((sport) => {
return (
<SportItem icon= {sport.colorIcon} text = {sport.name} onClick={this.handleClick()} key= {sport.id}/>
)
})


A single list item



   <div className=display-type icon-pad >
<div className=icons link>
<img className=sport-icon src={icon}/>
</div>
<p className=text-center>{text}</p>
</div>


I am not able to figure out what to do with handleClick so that If I click on a particular list it gets highlighted.


More From » html

 Answers
31

Keep a separate state variable for every item that can be selected and use classnames library to conditionally manipulate classes as facebook recommends.



Edit: ok, you've mentioned that only 1 element can be selected at a time,it means that we only need to store which one of them was selected (I'm going to use the selected item's id). And also I've noticed a typo in your code, you need to link the function when you declare a component, not call it



<SportItem onClick={this.handleClick} ...


(notice how handleClick no longer contains ()).



And now we're going to pass the element's id along with the event to the handleClick handler using partial application - bind method:



<SportItem onClick={this.handleClick.bind(this,sport.id} ...


And as I said we want to store the selected item's id in the state, so the handleClick could look like:



handleClick(id,event){
this.setState({selectedItemId: id})
...
}


Now we need to pass the selectedItemId to SportItem instances so they're aware of the current selection: <SportItem selectedItemId={selectedItemId} ....Also, don't forget to attach the onClick={this.handleClick} callback to where it needs to be, invoking which is going to trigger the change of the state in the parent:



<div onClick={this.props.onClick} className={classNames('foo', { myClass: this.props.selectedItemId == this.props.key}); // => the div will always have 'foo' class but 'myClass' will be added only if this is the element that's currently selected}>
</div>

[#60941] Sunday, August 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brennanm

Total Points: 510
Total Questions: 103
Total Answers: 95

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
;