Home > database >  Unable to Deselect the Previous item, when clicked on another Item using Reactjs
Unable to Deselect the Previous item, when clicked on another Item using Reactjs

Time:07-24

I have list of items and I am changing the background color when I clicked on that item... I need to change only the current Selected Item only , Previous selected Item should deselect... Now here, all items are getting changed when I clicked on each item... How can I solve this?? Can anyone help me in this ??

Here is my code

const Time = () => {

  const [selectedItem, setSelectedItem] = React.useState();
  const handleSelect = (event,selectedItem) => {
    setSelectedItem(selectedItem);
    event.target.style.backgroundColor = 'black';
    event.target.style.color = 'white';
};
 
  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 target' key={time} 
                  onClick={(event) => handleSelect(event,time)}>{time}</p>;
                })}
              </div>
            );
          })}
        </div>
        <div>{selectedItem}</div>
        <div className='new_Date'>PICK A NEW DATE</div>
      </div>
    </div>
  );
};

CodePudding user response:

you have to first change color for all the element to default color. Then you have to change the current element color to desired color.

CodePudding user response:

U can struct Ur time data to an object like this...

{text:"",selected:false}

and use selected property flag in data then assign a class conditionally into items based on that flag. then in clicking iterate Ur list and make all the flags false except the selected one.

function selectFn(selectedItem) {
  data.forEach((item) => {
    item.selected = false;
  });
  selectedItem.selected = true;
}

and UR template be some

... 
{chunks.map((timeslot) => {
    return (
      <div key={timeslot} className="inline">
        {timeslot.map((time) => {
          return <p className={`timeslots target ${time.selected ? "selectedClass" : ""}`} key={time.text} 
          onClick={(event) => selectFn(time)}>{time.text}</p>;
        })}
      </div>
    );
  })}
...

the css stuff..

.selectedClass{
    background:black;
    color:white;
}
  • Related