Having trouble unselecting the previous item when selecting a new item in Reactjs

I have a list of items and I want to change the background color of the currently selected item only. The previously selected item should deselect. However, at the moment, all items are changing when I click on each one. Can anyone help me solve this issue?

Below is my code snippet:

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

Answer №1

You can structure your time data into an object like so...

{text:"", selected:false}

Then, use the selected property flag in the data to assign a class conditionally to items based on that flag. When clicking, iterate through your list and set all flags to false except for the selected one.

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

And your template could look something like this:

... 
{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>
    );
  })}
...

Here's the CSS styling for the selected class:

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

Answer №2

To begin, reset the color of all elements to the default shade. Next, adjust the color of the current element to the specified hue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

Exploring jQuery functionalities for dynamic selector input

I have encountered a scenario where I must use dynamic ID's in the format of functionalDescription_IDNUMBER across my page. It is necessary to target specific areas based on the unique IDNUMBER associated with the clicked object. However, I am looking ...

Next.js encountered an API resolution issue while uploading a file, resulting in no response being

Even though my code is functioning properly, a warning appears in the console: The API call was resolved without sending any response for /api/image-upload This particular endpoint is responsible for uploading an image to Digital Ocean's object sto ...

Express Validator is ineffective, consistently returning a value of 'undefined' with the message: 'Value is not valid'

I am facing an issue with using Express Validator to validate an async POST query on the server side in my PERN stack application. Despite setting up the validation checks, Express Validator seems to always return the same response regardless of the input ...

Adjust link when scrolling through the webpage

I am looking to update the URL while scrolling instead of changing the menu class. Here's the reference I found: https://codepen.io/anon/pen/LdLgNo I made some modifications by adding push state, but I'm facing an issue with a fixed header. I ...

Integrating external JavaScript libraries into Ionic using the correct process

For the last few months, I have been utilizing jQuery Mobile for a hybrid app. Now, I am interested in exploring Ionic and Angular.js, so I am attempting to reconstruct it. My current JQM application relies on xml2json.js, but I do not have any experience ...

When the screen size changes, the sidebar in Bootstrap 5 smoothly reveals hidden content

I've been working on a sidebar design and everything seems to be going well so far. However, I've encountered an issue that has been giving me trouble for days now. Whenever I display a new page and then resize the screen, the content of the page ...

comprehending the concept of express and mastering its usage

Can you confirm if my understanding is correct? 1) So, when I write this line of code... const express = require(“express”) I am assigning a "Class" to the variable express. 2) And then, when I call this function... express.jason() Am I correctly ...

Can JavaScript values be passed into CSS styles?

I am currently working on dynamically updating the width of a CSS line based on a JavaScript value (a percentage). The line is currently set at 30%, but I would like to replace that hard-coded value with my JavaScript variable (c2_percent) to make it mor ...

There is no class present in the @Apply layer with Tailwind styling

I've been searching for what seems like a simple solution, but I can't seem to find it. While researching similar issues, I noticed that people were having problems with the Hover style and extra white space after it, which is not the issue in my ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

Are you familiar with using double conditional rendering in a React application?

Currently, I am in the process of creating a small clothing store application using React as a way to expand my skills. One feature I have implemented is a filter by price section. However, I am looking for a solution to handle cases where no items fall wi ...

What is the best way to merge several fetchMore functions within Apollo?

Can Apollo run multiple fetchMores simultaneously? I have a complex hook that executes two queries and combines their results into a single array. This is how it looks: export const useDashboardState = (collection: string) => { // Getting parameters ...

retrieve the value of a text form using jQuery and its corresponding id

I need help with a basic HTML form that includes jQuery. My goal is to: 1) Retrieve the value into a JavaScript variable. 2) Send it as JSON to a server. Here is the form: <div data-role="main" class="ui-content"> <data=role "form" ...

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

Hover over images for cool effects

Check out the code snippet I created on this link The current functionality enlarges images by 20 percent and overlaps into the table on hover. How can I enlarge both the image and table dimensions simultaneously? Below is the HTML code: <table borde ...

Is it possible for jQuery UI Dialog to function similar to an iFrame?

Is there a way to set up my dialog box with a form so that when the form is submitted, only the dialog box changes instead of the browser location? ...

"Encountered an issue while attempting to load resource: net::ERR_CONNECTION_REFUSED" for the assets, CSS, app.js, and vendor.js files during production (using React, Babel,

Currently, I am in the process of setting up a replica of the steemit client from https://github.com/steemit/steemit.com. During development, everything seems to work fine. However, when attempting to run the same setup in a production environment using t ...

Dropdown menu for selecting state in multiple countries built with React JS

In my project, I'm attempting to create a dropdown menu that lists multiple countries along with their associated states by mapping over an array. The sample data from the array is shown below: [ { "country" : "USA", ...

Why does the event fail to trigger in an Angular 5 Kendo grid when the last character is deleted from the input box?

I have implemented a multi-filter in my Kendo Grid for an Angular 5 application. However, I am facing an issue where the event is not firing when the last character is deleted from the input box. How can I resolve this issue? For example, if I type ' ...