简体   繁体   中英

Change Color of a selected item in an array

Suppose I am mapping in array which looks like this (I am using React)

 <div className="contact-display">                                    
          { this.contactList.length > 0 ? this.contactList.map(x => {
            return (
                <div className="contactlist-individual"> 
                   <img src={x["image"]}  width="40" height="40" /> 
                      <div className="contact-list-text">
                         <p className="contact-list-para-name">  {x["firstName"]} {x["lastName"]}</p>
                          <p className="contact-list-para-number"> {x["number"]} </p>
                      </div>
                    </div>
                   )}) : null
               }
 </div>

Here, my div with className: contactlist-individual have following css styles

.contactlist-individual {
    padding-left: 2%;
    display: flex;
    flex-direction: row;
    align-items: center; 
    border-bottom: 1px solid #E0E0E0;
    width: 100% !important;
}

(and I change the background-color: #EEEEEE; on hover), Now, when I select/click any time on of the element mapped through array.map , I want to change it's color from white to say green and thereafter when someone clicks on another element in that mapped array, I went to set the previous selected element back to normal and change the new selected mapped element color to green

Question: Can someone please help me in figuring out how i can achieve this?

Update: Immediately off my head, I can think of s, assigning unique ID dynamically (using index from map) and then using onClick event to trigger the function which selects that mapped element using getElementById from Vanila JS and then Changing this color.

Can someone suggest a better alternate?

One way around it is to have a click handler for each item in the list and set the active state for the element on click.

It is not a good idea to have a mix of updating the DOM using javascript directly.

toggleState = id => {
    let updatedList = this.state.contactList.map(x => {
      if (x.id === id) {
        x.active = true;
      } else {
        x.active = false;
      }

      return x;
    });

    this.setState({
      contactList: updatedList
    });
  };

Example - https://codesandbox.io/s/n9x5wyp0m0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM