Tips for altering the background shade of a chosen element within a list in ReactJS

Can someone assist me in changing the background color of a selected item from a list and retrieving the value of the selected item? Any help would be greatly appreciated. Thank you!

Below is the code for 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>
  );
};

Answer â„–1

There are potential alternative solutions, one of which involves incorporating the following code snippet into your paragraph:

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

In your handler function, you can then manipulate the element by assigning a custom class such as selected, or by directly changing its background.

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

Alternatively: Explore another method here: https://codesandbox.io/s/select-list-item-example-zu3qb7?file=/src/App.js

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

react-checkbox-tree issue with children not being checked

I recently implemented the react checkbox tree component in my project. Below is an example of a treeview with checkboxes: const nodes = [ { value: "mars", label: "Mars", children: [ { value: "phobos ...

Verifying the "select" dropdown option prior to final submission

My website features multiple select dropdowns that require validation before submission. For instance, there may be a situation where seven select dropdowns are present as described below. My desired validation criteria is: If there are 5 or more "sel ...

Is there a way to receive notifications on an Android device when the real-time data updates through Firebase Cloud Messaging (FC

I am attempting to implement push notifications in an Android device using Firebase Realtime Database. For example, if an installed app is killed or running in the background, and a user posts a message in a group (resulting in a new child being added in t ...

Is there a way to customize the default settings for a blueprint’s menu item?

https://i.sstatic.net/aNeJY.jpg In my react project, I implemented the Menu using MenuItem from '@blueprintjs/core'. The issue I encountered is that when hovering over a Menu item with children, they open from the right side. Is there a way to m ...

ngResource transformResponse guide on dealing with both successful and erroneous responses

When my API, built using expressJS, returns JSON data as a regular response, everything functions smoothly. However, when an error occurs, it returns an error code along with plain text by simply invoking res.sendStatus(401). This poses a challenge on my ...

Retrieve all attributes of an element with the help of jQuery

I am attempting to extract all the attributes of an element and display their names and values. For instance, an img tag may have multiple unknown attributes that I need to access. My initial idea is as follows: $(this).attr().each(function(index, element ...

Suggestions for resolving the issue of my header being truncated on mobile browsers?

I am facing an issue with my header and need assistance in fixing it. The problem occurs when scrolling down, as it cuts off a part of the header, but returns to normal when scrolling back up. I suspect the hamburger menu might be causing this issue becaus ...

Separate a string into individual parts while also including the separators as their own values within

Looking for help with extracting numbers and operators from basic math equations. Is there a way to split each number into an array while keeping the operator separate? "123/12*312+4-2" The desired output is as follows: ["123", "/", "12", "*", "312", "+ ...

Is there a way to embed a JS media query inside the sticky navbar function for both the onscroll and onclick events?

I've been exploring media queries in JavaScript, and it seems like they work well when the window is resized. However, when nested within onscroll and onclick functions, things start to get a bit tricky. If you run the following code and resize the w ...

Tips for properly aligning blockquote opening and closing quotation marks

We are currently implementing custom styles for beginning and end quotes in a string using the <blockquote> tag. However, we are having issues with the alignment, as the opening quote appears before the text and the closing quote is at the end of the ...

Issues encountered with executing `npm run dev`

Encountering an issue with vueJs webpack while trying to run it on the server using the command: npm run dev. Unfortunately, an error message keeps popping up. Can anyone offer guidance on how to resolve this issue? Your help is greatly appreciated! Erro ...

Selecting specific elements from an array in JavaScript can be achieved by using various methods and techniques

Currently working on a quiz incentive system where users earn rewards based on the number of correct answers they input. The example array below shows the possible range of correct answers: var rightAnswers = ['a', 'b', 'c' ...

Can you identify the issue with the phase control in my sine wave program?

I have recently developed an interactive sine wave drawing web application. Below is the code snippet for reference: const canvas = document.getElementById("canvas"), amplitude_slider = document.getElementById("amplitude_control"), wavelength_slider ...

Refreshing ApolloClient headers following a successful Firebase authentication

I am encountering an issue while trying to send an authorization header with a graphql request when a user signs up using my React app. Here is the flow: User signs up with Firebase, and the React app receives an id token. User is then redirected to ...

Bring in personalized tag to TypeScript

I am working on a TypeScript file to generate an HTML page. Within this code, I want to import the module "model-viewer" and incorporate it into my project. import * as fs from "fs"; import prettier from "prettier"; import React from "react"; import ReactD ...

Authentication in HTML5 beyond the internet connection

Seeking feedback on the most effective way to control access to an HTML5 application that is primarily used offline. This application utilizes IndexedDB, local, and session storage to securely store data for offline use, all served via HTTPS. The main go ...

Guide to importing the Slider Component in React using Material-UI

I am trying to incorporate the Slider Component from @material-ui/core into my React project. However, when I attempt to import the Slider using this code: import Slider from '@material-ui/lab/Slider';, it gives me an error stating Module not fou ...

Troubleshooting a problem with media queries causing display:none issues

Check out this HTML email template code we've been testing on various email clients including Gmail, Yahoo, Outlook, Rediffmail, iPhone, and iPad. The template consists of two table blocks - one for web browsers and the other for mobile devices like ...

What is the rationale behind excluding the constructor in the Time Travel section of the ReactJS tutorial?

As stated in this particular tutorial: The next step is to pass the squares and onClick props from the Game component to the Board component. With a single click handler in Board for multiple Squares, we need to include the location of each Square in the ...

Maximizing Efficiency with Single Click Line Editing in the Newest Version of jqgrid

There seems to be an issue with single click inline row editing in the latest free jqgrid from github master. BeforeSelectRow, clicking on a row to start inline editing causes an exception: Uncaught TypeError: Cannot read property 'rows' of unde ...