I used the map function in React to display a group of items. When an item is clicked, it triggers an onClick function that affects all items. However, I only want the

Having an issue where I need to change the border-color of a single item in a list when clicked on. The items are displayed using the map function and styled components. When I try to use useState to achieve this, it updates every item in the list instead of just one. How can I make sure only the clicked item's color is changed?

    <div className="specs-container">
            {specification.map((item, index) => {
              return (
                <div
                  className="single-spec"
                  key={index}
                  id={item}
                  style={{
                    backgroundColor: `${item}`,
                    color: `${item}` === "Black" ? "white" : "",
                    fontSize: `${id === "Capacity"}` ? "0.7rem" : "20px",
                    border: `1px solid ${bgcolor} `,
                  }}
                  onClick={(e) => {
                    console.log(e.target.id);
                    let item = specification.filter((item) => item === e.target.id);

                    console.log(item);
                    
                    // if (e.target.id === item[0]) {
                    //   setBgcolor("green");
                    // }
                  }}
                >
                  {id === "Capacity" ||
                  id === "Size" ||
                  id === "With USB 3 ports" ||
                  id === "Touch ID in keyboard"
                    ? `${item}`
                    : ""}
                </div>
              );
            })}
          </div>
        </SpecWrapper>


   

https://i.sstatic.net/oE3JV.png

Answer №1

One approach is to simply save the index of the selected item in the state and then compare it with the index in the map in order to modify the background color

const [selected, setSelected] = useState();
...
...
 <div
   className="single-spec"
   key={index}
   id={item}
   style={{
     backgroundColor: {selected===index ? 'green' : `${item}`, // some item has color name
     color: `${item}` === "Black" ? "white" : "", // if item's color === black render white
     fontSize: `${id === "Capacity"}` ? "0.7rem" : "20px",// based on category
     border: `1px solid ${bgcolor} `, // here I have stucked
              }}
  onClick={()=>setSelected(index)}
>

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

Display text on top of an image using HTML

I'm having trouble creating a submit button for my form that includes both an image and text. I've tried multiple methods, but encountered some issues. Here's the HTML code: <form action="www.page.html" method="post> some text <spa ...

The font sizes appear larger when styled with HTML compared to using Photoshop

When I view my <nav> element in Chrome, the font size of each list element appears much larger than it was originally designed in Photoshop. The font is displaying 23px wider in Chrome compared to Photoshop, even though my resolution is set at 72dpi ...

Troubleshooting Problems with CSS Span Placement

Challenges with Span Positioning in CSS Currently, I am encountering difficulties while working on the index.html.erb file for an example Rails website. Below is a snippet of the HTML code I am struggling with (please note that this is simply a fabricated ...

Ensure that Google Tag Manager (GTM) delays the pageview until the SPA URL title is available

I'm dealing with a React SPA that manages all the URL titles on the frontend, so the historyChange event registered on GTM captures the visited URLs along with their titles correctly. However, I've noticed that on the initial load of the SPA, su ...

Encountering a compile error with a Next.js React project that cannot be resolved

Encountered an issue while refreshing my project with the command "npm run dev" and reloading the site locally. The console displays "Compiled /not-found" and the site fails to load completely. In addition, none of the elements animated via framer motion ...

Utilizing React with Emotion to Customize Font Sizes

In my React app, I am using emotion to style and display the formula for compound interest. Within my render() method, I am returning the following: <div css ={equation}> <p> P (1 +</p> <p css={fraction}> <span classNa ...

Utilizing ng-options within an ng-repeat to filter out previously chosen options

Facing a simple problem and seeking a solution. I am using ng-repeat to dynamically create select boxes with ng-options displaying the same values. The ng-repeat is used to iterate through model options. <div data-ng-repeat="condition in model.condit ...

Utilizing dropdown menus in React to refine data pulled from an API

How can I use a dropdown menu to filter results from an API? Currently, my select tag looks like this: <select value={selectMonthFilter} onChange={e=> setSelectMonthFilter(e.currentTarget.value)}> {console.log(selectMonthFilter)} <opti ...

The command `python3 manage.py findstatic` is unable to locate the static file

I have been struggling to incorporate static files into my project, but the CSS is not loading. I tried using findstatic but Django is unable to locate any static directory: https://i.sstatic.net/jRgzx.png https://i.sstatic.net/7VG0x.png In a different pr ...

jquery's each method is not functioning as intended and causing unexpected issues

I'm in the midst of developing a website, and one section requires users to input their details into a form. My goal is as follows: When a user clicks the submit button with any empty fields, I want a span element (initially set to display none in CS ...

Tips for deleting "Category: [category name]" in Wordpress

I have attempted various solutions found in previous threads, but none of them seem to work for me. Here is a screenshot I am looking to remove the text from the header in the category and only display [category name]. Can anyone assist me with this, ple ...

What is the best way to pass props values to styled components using Emotion in react?

Recently, I started exploring MUI and React, and I am working on creating a reusable input textbox component instead of building it from scratch every time. My current challenge is setting the width value by passing it as a prop. How can I achieve this? ...

Switching over from an external style sheet to inline elements can be tricky, especially when it comes to integrating "dropdown" styles properly

I successfully created a stylish menu using a specific style sheet, but now I'm facing issues when trying to incorporate this menu into web pages with different style requirements. Realizing that loading the style sheet onto these new pages wreaks hav ...

Can you explain the distinction between a standard $.post() method sending strings versus one sending a file?

Curious as to why I am unable to upload a file through JQuery using the $.post() function? Are there any modifications that can be made to the request in order to enable file uploads? $.post(url, { file: fileName, path: "/uploaded_files" }, function (res ...

When trying to access a string value for an ID, I encountered an error stating "Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)"

Currently, I am working on a project using React and Typescript. My goal is to retrieve a specific string with the key name id from an array of ten objects that contain the id. The screenshot displaying the code produces the desired output in the console; ...

The Vue 2.0 instance seems to be failing to listen to events emitted by vue-router components

Currently, I am working with Vue 2.0-rc.6 and Vue-router 2.0-rc.5, the latest versions available. I attempted to use this.$emit('custom-event') in one of my router components and this.$on('custom-event', () => { console.log('I ...

What is the best way to have child divs occupy the entire area of the parent div while also accounting for margins

I am facing a challenge with arranging child divs inside a parent div that has a specific width. Even though I am using isotope to arrange them, the layout modes do not work well for me in terms of spacing. My goal is to have the child divs fill the space ...

Is there a way for me to store the output of an AJAX call?

One of the challenges I'm facing involves an AJAX request: $.ajax({ url: 'script.php?val1=' + value1 + '&val2=' + value2, dataType: "json", success: function (data) { var newValue1 = data[0]; ...

Establish a straightforward connection between the current value of "this" and the higher scope in React in order to adjust the state accordingly

Is there a way to ensure that the value of 'this' is never undefined? import React, { Component } from "react"; import { render } from "react-dom"; import Hello from "./Hello"; import "./style.css"; class App extends Component { constructor() ...

Pass data that has been asynchronously resolved from the parent component to the child component using props in Vue

Main component: <template> <div> <Nav :data="data" /> </div> </template> <script lang="ts"> // ... imports removed for clarity @Component({ components: { Nav: () => import('@/components/Nav.vue&ap ...