简体   繁体   中英

How to change the background Color of selected item in a list using ReactJS

Here I need to change the background color of an selected item from a list and get the value of the selected Item as well , Please Can anyone help me in this.. Thanks in Advance

Here is my Component

const Time = () => {
  const dataTime = useMemo(() => TimeData, []);
  const chunks = useMemo(() => {
    const _chunks = [];
    const tmp = [...dataTime];
    while (tmp.length) {
      _chunks.push(tmp.splice(0, 3));
    }
    //console.log(_chunks);
    return _chunks;
  }, [dataTime]);

  return (
    <div className="Main-Section">
      <div className="First-Section">Time</div>
      <div className="Second-Section">
        <div className="date_title">Wednesday , June 13</div>
        <div className="time_Slots">
          {chunks.map((timeslot) => {
            return (
              <div key={timeslot} className="inline">
                {timeslot.map((time) => {
                  return <p className='timeslots' key={time}>{time}</p>;
                })}
              </div>
            );
          })}
        </div>
        <div className='new_Date'>PICK A NEW DATE</div>
      </div>
    </div>
  );
};

I beleive there may be better solutions as well, but you could add something like this to your paragraph:

{timeslot.map((time) => {
  return <p
    className='timeslots'
    key={time}
    onClick={(event) => yourHandlerFunction(event, time)}
  >
    {time}
  </p>;
})}

and then in your handler function you could add a custom class to your element eg selected or just simply change its background directly

const yourHandlerFunction = (event, time) => {
  event.target.classList.add('selected');
  // ...
};

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