ReactJS: Want to update card design by utilizing the onClick event handler

Currently, I am aware that there will be a need to refactor this code later on to separate things into their own components. However, due to time constraints, I have to wire this up as is at the moment. To achieve this, I utilized array.map() to create card elements from a JSON object used for testing purposes. The goal is to use an onClick function on a card <div> to save identifiable information such as 'offerid' into the component state and then compare the id in the state with the current card. If they match, I intend to add 'cardActive' as the className on the div so that only that specific card changes color. Unfortunately, I am unsure of how to accomplish this. As it stands now, all card stylings get updated regardless of which card is selected. Below are my React component and corresponding CSS. Any assistance provided would be greatly appreciated.

React

import React, { Component } from 'react';
import Grid from '@material-ui/core/Grid';
import './Button.css';

class UsersList extends Component {
    constructor(){
        super();

        this.state = {
            cardActive: false,

            customers:
            [
                {
                    "CustomerId": "1",
                    "LastName": "Doe",
                    "FirstName": "Jane",
                    "Address": {
                      "Address1": "1811 Chestnut Street",
                      "Address2": null,
                      "City": "Philadelphia",
                      "State": "Pennsylvania",
                      "Zip": "19103"
                    },
                    "Offers": [
                      {
                        "OfferId": "Offer1",
                        "Name": "Offer 1",
                        "Products": [
                          {
                            "ProductId": 1,
                            "ProductName": "Stuff"
                          },
                          {
                            "ProductId": 2,
                            "ProductName": "More stuff"
                          }
                        ],
                        "Price": "$1"
                      },
                      {
                        "OfferId": "Offer2",
                        "Name": "Offer 2",
                        "Price": "$2",
                        "Products": [
                          {
                            "ProductId": 3,
                            "ProductName": "A lot of stuff"
                          },
                          {
                            "ProductId": 4,
                            "ProductName": "And then there was stuff"
                          }
                        ]
                      },
                      {
                        "OfferId": "Offer3",
                        "Name": "Offer 3",
                        "Price": "$3",
                        "Products": [
                          {
                            "ProductId": 5,
                            "ProductName": "Good grief would you look at all this stuff"
                          },
                          {
                            "ProductId": 5,
                            "ProductName": "What a great deal for stuff"
                          }
                        ]
                      }
                    ]
                  }
              ]
        }
    }

    selectCard(){
        this.setState({ cardActive: !this.state.cardActive })
    }


    render (){
        let card_class = this.state.cardActive ? "cardActive" : "card";
        return (
            <div>
                {this.state.customers.map((customer, index) => {
                    return  <div key={index + customer.CustomerId}>
                                <h2>Customer</h2>
                                <hr></hr>
                                    <h3 >Name: {customer.LastName}, {customer.FirstName}</h3>
                                    <h3 >Customer ID: {customer.CustomerId}</h3>
                                    <h3 >
                                    Address: 
                                    <br></br>
                                    {customer.Address.Address1}
                                    <br></br>
                                    {customer.Address.City}, {customer.Address.State} {customer.Address.Zip} 
                                    </h3>
                                    <br></br>
                                    <h2>Available Offers</h2>
                                    <Grid container spacing={24} justify="center"> 
                                    {customer.Offers.map((Offer,index) => {
                                        return <div key={index + Offer.OfferId} onClick={this.selectCard.bind(this)}>
                                                <Grid item xs={12}>
                                                <div className="card" class={card_class}>
                                                    <div className="container">
                                                        <h5><b>{Offer.OfferId}</b></h5> 
                                                        <h2>{Offer.Name}</h2>
                                                        {Offer.Products.map((Product, index) => {
                                                            return <div key={index + Product.ProductId}>
                                                                    <p>+ {Product.ProductName}</p>
                                                                  </div>

                                                        })}
                                                        <h3>{Offer.Price}</h3> 
                                                    </div>
                                                </div>
                                                </Grid>
                                            </div>
                                    })}

                                    </Grid>

                            </div>

                })}
                <button className="navbuttonSelected">Submit</button>
            </div>
        )
    }
}

export default UsersList

CSS

  .card {
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transition: 0.3s;
    border-radius: 5px; /* 5px rounded corners */
    margin-left: 70px;
    margin-right: 70px;
    margin-bottom: 5%;
    cursor: pointer;
  }

  .cardActive {
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
    transition: 0.01s;
    border-radius: 5px; /* 5px rounded corners */
    margin-left: 70px;
    margin-right: 70px;
    margin-bottom: 5%;
    background: #0c72c5 !important;
    color: white !important;
    cursor: pointer;
  }

  .cardActive:hover {
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
  }

  .card:hover {
    box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
  }

Answer №1

Assigning an ID to the chosen card:

selectCard(id) {   
  this.setState({ selectedCard: id });
}

Modify how onClick is invoked and add a specific class when

Offer.Id === this.state.selectedCard

return (  
 <div
   key={index + Offer.Id}
   onClick={() => this.selectCard(Offer.Id)}
 >
   <Grid item xs={12}>
     <div
      className={Offer.Id === this.state.selectedCard ? "activeCard" : "regularCard"}>

See it in action here: https://codesandbox.io/s/mjryv01528

Answer №2

If you're looking for solutions to your issue, I have a couple of different approaches that may help.

Here is the first approach:

  • Within your selectCard function, make sure to not only store the cardActive status but also save the card's ID in the state.

  • In your render method, consider using the ID (stored in the state) within the map function to determine whether the card should have the cardActive class applied.

  • By following this approach, only one card will be able to have the cardActive class at a time, preventing multiple selections.
  • Additionally, ensure that the ID is only set in the state when the card is selected and not deselected.

Now, let's explore the second approach:

  • Within the offers object of the customer, add a new property called isActive along with the existing fields. Utilize this property in your map method to toggle between applying the cardActive class or the normal class.
  • Whenever a card is selected, update the isActive property of that specific card. This can be achieved by passing the offerObject to the selectCard method and updating the isActive property within it, or by passing a unique identifier and modifying the customers object accordingly.
  • With this method, you'll have the ability to select multiple cards as each customer maintains its own isActive status, rather than relying on a single cardActive variable.

Answer №3

...
constructor(){
    super();

    this.state = {
        selectedCard: "",

        clients: [...]
    }
    this.chooseCard = this.chooseCard.bind(this);
    this.getCardStyle = this.getCardStyle.bind(this);
}

chooseCard(clientId){
    this.setState({ selectedCard: clientId })
}

getCardStyle(clientId) {
    const { selectedCard } = this.state;
    return clientId === selectedCard ? 'selectedCard' : 'card';
}

render() {
...
    client.Clients.map((Client,index) => {
        return <div key={index + Client.ClientId} onClick={() => this.chooseCard(Client.ClientId)}>
            <div item xs={12}>
            <div className="card" class={this.getCardStyle(Client.ClientId)}>
                <div className="container">
                    <h5><b>{Client.ClientId}</b></h5> 
                    <h2>{Client.Name}</h2>
                    {Client.Products.map((Product, index) => {
                        return <div key={index + Product.ProductId}>
                                <p>+ {Product.ProductName}</p>
                              </div>

                    })}
                    <h3>{Client.Price}</h3> 
                </div>
            </div>
            </div>
        </div>
    })
...

}

Instead of using a boolean value to store the selected card, this component keeps track of it through selectedCard. The chooseCard function updates the state with the chosen card while getCardStyle determines its style.

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

Tips for positioning a Wordpress navigation bar to the right of a logo

My goal is to position the navigation bar next to the logo in my Wordpress theme using Underscores. I have successfully aligned the primary navigation and the logo as desired with the following CSS: .main-navigation { position: relative; float: ri ...

Creating a Form Layout with Bootstrap - Organizing Text Boxes and Text Areas

https://i.sstatic.net/oqRwR.jpg In the image above, I need to adjust the position of the textbox to align it with the TextArea. Is there a Bootstrap class that can help me achieve this? My current version of Bootstrap is 3.3.6. HTML &l ...

Import data into Bootstrap table from an external source

I am having trouble styling the table loaded from the table.html file onto the index page. Even after loading the table, the styles from bootstrap classes are not applied. What could be causing this issue? Importing bootstrap libraries directly into the ta ...

Experiencing a problem during the installation of npm express for testing purposes

Having trouble installing supertest as I keep receiving errors in the terminal. When I run 'supertest -v', it says command not found. Even after installing, I encounter the following error. Any suggestions would be greatly appreciated. I attempte ...

Implement Cross-Origin Resource Sharing in Angular frontend

I am facing an issue with two microfrontends running on different ports (4200 and 4201) where one frontend is unable to access the translation files of the other due to CORS restrictions. To overcome this obstacle, I created a custom loader in my code that ...

When utilizing React client-side rendered components, the state may fail to update while the script is actively running

I am currently facing an issue for which I don't have a reproducible example, but let me explain what I'm trying to do: class MyComponent extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() ...

Having an issue with Jquery selector where the text does not match

HTML Code <select id="myDropdown"> <option selected="selected" value="0">default</option> <option value="1">bananas</option> <option value="2">pears</option> </select> Javascript Function setDr ...

Verifying the format of an object received from an HTTP service using a TypeScript interface

Ensuring that the structure of the http JSON response aligns with a typescript interface/type is crucial for our javascript integration tests against the backend. Take, for example, our CurrentUser interface: export interface CurrentUser { id: number; ...

Is there a way to retrieve just one specific field from a Firestore query instead of fetching all fields?

I am experiencing an issue where I can successfully output all fields in the console, but I only want to display one specific field. In this case, I am trying to retrieve the ID field but I am encountering difficulties. Below are screenshots illustrating m ...

Elegant rounded bordered sidebar design to highlight selected navigation items using HTML and CSS

I am looking to replicate the sidebar design displayed in the image below by using HTML and CSS. While I have successfully rounded the borders on the left side of a selected link, I am stuck when it comes to rounding the borders on the right side. https:/ ...

Tips for implementing a draggable image within an <a-scene> by utilizing <a-assets> and <a-image> tags

Exploring the world of augmented reality for the web has been an interesting journey for me. I have been experimenting with aframe-ar.js and aframe.js to create a unique experience. One of the challenges I faced was making an image draggable within the & ...

Error encountered: Unexpected token when defining inline style in React

When attempting to prevent scrolling on the page by using style='overflow-y: auto;': render() { return ( <div style={{overflow-y: auto}}> <div>{this.props.title}</div> <div>{this.props.children}& ...

Explore in MegaMenu Pop-up

At my workplace, the internal web portal features a MegaMenu with a popup menu that includes a Search input field. The issue I am encountering is that when a user starts typing in the search bar and moves the mouse off of the megamenu, it disappears. It ...

Error message 2339 - The property 'toggleExpand' is not recognized on the specified type 'AccHeaderContextProps | undefined'

When utilizing the context to share data, I am encountering a type error in TypeScript stating Property 'toggleExpand' does not exist on type 'AccHeaderContextProps | undefined'.ts(2339). However, all the props have been declared. inter ...

Create custom styles for Android applications using CSS or themes programmatically

As I work on developing an application, I am interested in implementing a unique approach... To retrieve a CSS file from the server and apply it to the activity layout. To create a string file for styling or theming and integrating it into the layout. I ...

JavaScript Class experiencing issues with returning NAN when using the Multiplication method

Currently, I have a JavaScript Class with a multiplication method that aims to multiply all elements of an array excluding those that are undefined. To achieve this, I utilized a for loop to check the data type of each element (ensuring it is a number) and ...

Instructions for sending a PNG or JPEG image in binary format from a React app to a Node.js server

I am in the process of transferring a file from a react web app to a node.js server. To begin, I have an HTML input of type file where users can upload their files. Once a user uploads a file, a post request is triggered to my Node.js server. Within my N ...

Experience the auditory bliss with Javascript/Jquery Sound Play

I am creating an Ajax-driven application specifically for our local intranet network. After each response from my Ajax requests, I need to trigger a sound in the client's browser. I plan to store a sound file (mp3/wav) on our web server (Tomcat) for ...

Tips for showcasing information entered into text fields within a single container within another container

After creating three divs, the first being a parent div and the next two being child divs placed side by side, I encountered an issue with displaying input values. Specifically, I wanted to take values from input text boxes within the second div (floatchil ...

Preserving data in input fields even after a page is refreshed

I've been struggling to keep the user-entered values in the additional input fields intact even after the web page is refreshed. If anyone has any suggestions or solutions, I would greatly appreciate your assistance. Currently, I have managed to retai ...