scripter scripter - 2 months ago 6
CSS Question

how to add css classes to a component in react?

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 = => {
return (
<SportItem icon= {sport.colorIcon} text = {} onClick={this.handleClick()} key= {}/>

A single list item

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

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


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,} ...

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

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}>