Customizing the appearance of map items in a React JS application

As a newcomer to reactjs, I am working with an array that looks like this:

const mediumNames = ["TAMIL Medium", "ENGLISH MEDIUM"]

Using the above code, I have created two cards:

const [selectedMediumColor, setSelectedMediumColor] = useState('')

<div>
    {mediumNames.map((text, index,) => (

    <Card style={{ border: selectedMediumColor }} onClick={() => onClickMedium(text,index)} >
        <div >
            <img className={classes.imginCardBoard} src={TNlogo}></img>
                <Typography className={classes.textinCardBoard} > { text} </Typography>
        </div>
    </Card>
    ))}
</div>

I am trying to implement a scenario where clicking on a card in ReactJS changes its border color. The first card should have a blue border when selected while the second card should have a white one, and vice versa.

Below is the function I came up with:

 const onClickMedium = (medium,indexno) => {
        console.log(medium)
        console.log(indexno)

        if (medium === "TAMIL Medium") {
            
            selectedMediumColor('2px solid #00adb5')
        }
        else {
            selectedMediumColor('')
        }
    }

The issue I am facing is that the color setting applies to both cards. See the image here: enter image description here

I'm seeking guidance on how to modify this functionality so that only one card's color is changed at a time. Any help or suggested solutions would be greatly appreciated. Thank you!

Answer №1

If you want to implement a solution where you can define the selected index, consider this method:

const [currentIndex, setCurrentIndex] = useState('')

 <div>
    {mediumNames.map((text, index,) => (

    <Card style={{ border: index === currentIndex ? '2px solid #00adb5' : 'none'}} onClick={() => setCurrentIndex(index)} >
        <div >
            <img className={classes.imginCardBoard} src={TNlogo}></img>
                <Typography className={classes.textinCardBoard} > { text} </Typography>
        </div>
    </Card>
    ))}
</div>

Answer №2

Like Harshit's suggestion, this method offers a way to achieve the desired outcome. However, it can be expanded further to accommodate more than two mediums in your situation.

const App = () => {
  const mediumNames = ["TAMIL Medium", "ENGLISH MEDIUM"];
  const mediumBorder = ["2px solid #00adb5", "2px solid red"];

  const [selectedMedium, setSelectedMedium] = useState("");
  const [selectedMediumIndex, setSelectedMediumIndex] = useState("");

  const onClickMedium = (medium, index) => {
    setSelectedMedium(medium);
    setSelectedMediumIndex(index);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        {mediumNames.map((text, index) => (
          <div
            style={{
              border:
                selectedMedium === text ? mediumBorder[selectedMediumIndex] : ""
            }}
            onClick={() => onClickMedium(text, index)}
          >
            <div>test</div>
          </div>
        ))}
      </div>
    </div>
  );
}

This approach allows you to manage any number of mediums with unique border styles for each medium.

Check out the sample on CodeSandbox

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

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

Clickable links and compliant W3C coding

Recently, I have encountered errors in the W3C validator due to the presence of "name" attributes in some <a> tags in my document. The validator flagged these attributes as obsolete. I am curious to know when and why this happened? Additionally, I n ...

Creating Responsive Social Icons using HTML and CSS

Currently working on my portfolio website, but encountered an error. Can someone assist me in making my social icons responsive? I need the icons to be responsive and aligned horizontally for the mobile version. Here is a visual of the issue with the desk ...

Adjusting the position of the arrow helper to create more space from the

I am currently working on achieving a specific goal. https://i.sstatic.net/XnAmo.png Instead of moving farther away from the object, the two arrow helpers seem to be shifted inward. How can I adjust their positioning to move them away from the object? B ...

When developing libraries in webpack, which dependencies should be considered as peer dependencies?

Our team is in the process of developing reusable React components. Each component will be packaged as an npm library with webpack. We are debating whether each library should declare its dependencies as peer dependencies and rely on the application to i ...

Switching the file format from HTML to .ASP resulted in the loss of the website's design elements and images

After initially creating an HTML file, I decided to rename it with a .asp extension for uploading online. To do this, I copied the original HTML file and moved it into a folder containing .asp files. However, after replacing the existing file, my website l ...

Unexpected behavior with animation duration in Safari

We have a project in the works that involves CSS animation. Our goal is to update the animation duration using JavaScript. Although this change is effective in most browsers, it seems to have trouble with Safari and iOS. Below is the code we are using to ...

Using jQuery, you can retrieve data from a specific sheet in Google Sheets API by executing a

Is there a way to access cells from different sheets within a Google spreadsheet? Currently, I am able to access a range of cells from the default first sheet using the following code: var url = 'https://docs.google.com/spreadsheets/d/' + spread ...

Assistance with Squarespace code injection: Enhancing hover effects on the Flat-Iron template

While browsing the index gallery, I noticed that the Flat-iron template has an opacity change when you hover over images. I'm curious if it's possible to reverse this effect so that the images remain at a low opacity until hovered over to reveal ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

Using a Custom Variable in PayPal Email Links

Currently, I am developing a compact integrated application for a project that does not involve using a form. In this particular project, the use of HTML is not necessary and instead, only a link can be passed to the browser. The purpose of this link is to ...

Merge JSON objects into an array

Is there a way to merge JSON objects when the initial object is: { "total": "2" } And the second one is: [ "player1": { "score": "100", "ping": "50" }, "player2": { "score": "100", "ping": "50" ...

Tips for enabling the background div to scroll while the modal is being displayed

When the shadow view modal pops up, I still want my background div to remain scrollable. Is there a way to achieve this? .main-wrapper { display: flex; flex-direction: column; flex-wrap: nowrap; width: 100%; height: 100%; overflow-x: hidden; ...

Creating a Custom Checkbox with HTML and Label

How can I position the label on top of a checkbox? HTML: <input type='checkbox' name='thing' value='valuable' id="thing"/> <label for="thing">Description</label> CSS: input[type=checkbox] { display:n ...

Encountering a problem with SVG integration in Gatsby with Typescript

In my current project, I am experimenting with using SVG in a Typescript page in Gatsby. To achieve this, I decided to utilize the Gatsby plugin called . //gatsby-config.js { resolve: "gatsby-plugin-react-svg", options: { ...

What is the best way to sort my map function alphabetically in React?

I have a JSON file : [ { "level_1": "music", "level_2": "rock", "level_3": "had-rock / metal" }, { "level_1": "music", "level_2": "rap& ...

Replacing an array element in React.js

Here is a React.js code snippet where I am trying to utilize an array called distances from the file Constants.js in my Main.js file. Specifically, I want to replace the APT column in the sampleData with a suitable value from the array distances extracted ...

Quick way to include id="" and class="" attributes to HTML elements using Sublime Text 2

Is there a way to configure Sublime Text 2 where inputting a . (dot) automatically generates class=" " and adding a # (hash) creates id=" " while typing an HTML opening tag? ...

Tips for verifying that a WebSocket message is a JSON string and preventing any JSON.parse errors

After diligently searching for a solution to handle invalid JSON.parse calls, particularly in the context of WebSocket messages without using the try/catch block due to performance concerns. I've successfully transitioned my RESTful API to a WebSocke ...

The secondary menu appears prominently above the primary menu

Here is my .html code : {% load i18n %} <div class="customer-context-menu closed {% if customer.gender == 0 %}male{% else %}female{% endif %}"> <b class="unselectable"> {{ customer.icon }} {{ user.get_full_name }} < ...