Switching an :active class using ReactJS

Currently, I am working on creating an onboarding screen where the user is required to select three or more items. Once the user clicks on an item, a purple overlay should remain visible.

For reference, this is what I have in mind: https://i.sstatic.net/r89UP.png

Sharing my code snippet below:

var RepeatModule = React.createClass({
   getInitialState: function() {
      return { items: this.props.items || [] }
   },
   componentWillMount: function() {
     console.log("componentWillMount()")
     this.setState({ items : data })
     console.log(data,"data is here");
   },
   handleClick: function (e, item) {
    this.setState({active: true});
   },
   render: function() {
      var listItems = this.state.items.map(function(item) {
         return (
            <ListItem item={item}/>
         );
      });
      return (
         <div className="flex-container">
             {listItems}
         </div>
      );
   }
});

/* Making the items stateless */
var ListItem = function(props) {
    var backgroundImage = {
      backgroundImage: 'url(' + props.item.pictureURL + ')'
    };
     return (
         <div className="block-grid-item">
          <a className="display-block card text-gray-darker">
            <div onClick={handleClick} style={backgroundImage} className="card-img-wrap m-xs-0 placeholder placeholder-landscape">
            </div>
            <div className="card-meta">
              <div className="vesta-hp-gifts-card-title text-gray-darker">{props.item.storeName}</div>
            </div>
          </a>
        </div>
     );
}

I seem to be facing an issue with maintaining the active state when attempting to implement it within my handleClick function.

Additionally, here is the CSS effect related to the hover functionality:

.card-img-wrap::after
  {
    background-color: #000;
    bottom: 0px;
    content: "";
    left: 0px;
    opacity: 0;
    position: absolute;
    right: 0px;
    top: 0px;
  }
  .card-img-wrap:hover::after
  {
    background-color: #000;
    bottom: 0px;
    content: "";
    left: 0px;
    opacity: 0;
    position: absolute;
    right: 0px;
    top: 0px;
    opacity: 0.6;
    background-color: #5450DC;
  }

Could anyone shed some light on why this setup is not functioning as expected? Any suggestions on how to accomplish this task effectively?

Answer №1

Be sure to pass the necessary properties to ListItem, such as handleClick:

render: function() {
      var listItems = this.state.items.map(function(item) {
         return (
            <ListItem handleClick={this.handleClick} item={item}/>
         );
      });
      return (
         <div className="flex-container">
             {listItems}
         </div>
      );
   }

These properties will then be accessible under props in the ListItem

var ListItem = function(props) {
    var backgroundImage = {
      backgroundImage: 'url(' + props.item.pictureURL + ')'
    };
     return (
         <div className="block-grid-item">
          <a className="display-block card text-gray-darker">
            <div onClick={props.handleClick} style={backgroundImage} className="card-img-wrap m-xs-0 placeholder placeholder-landscape">
            </div>
            <div className="card-meta">
              <div className="vesta-hp-gifts-card-title text-gray-darker">{props.item.storeName}</div>
            </div>
          </a>
        </div>
     );
}

Similarly, ensure that you handle the active prop appropriately by either managing it within ListItem or passing it through props from the parent component, depending on your requirements. Adjust the classNames based on the value of this prop.

Check out the jsFiddle for an example: https://jsfiddle.net/69z2wepo/67316/

Note that ES6 features are used in the code snippet to maintain context. You can also use bind or other methods to ensure that this.handleClick refers to the appropriate class function.

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

Achieve horizontal wrapping of div elements

Currently, I am developing a blog where search results for articles will be displayed within divs. The design of the website is completely horizontal, meaning that articles scroll horizontally. Creating a single line of divs is straightforward, but it&apo ...

VueJS is unable to access an array

Unable to access an array in Vue.js. console.log(this.ref_number_response[0]); When I try to access the array, it shows undefined. I'm puzzled by this... data(){ return{ ref_number_response: [], } }, methods:{ che ...

Identification of input change on any input or select field within the current modal using JavaScript

My modal contains approximately 20 input and select fields that need to be filled out by the user. I want to implement a JavaScript function to quickly check if each field is empty when the user navigates away or makes changes. However, I don't want t ...

Display only distinct items in a v-for loop in Vue.js

I am attempting to show icons based on specific v-for and v-if conditions. However, the icons are appearing multiple times when I only want them to display once. I attempted using v-if = 'index === 0', but this did not resolve the issue. <di ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

What is the best method for extracting string values from a JavaScript object?

I am working with JavaScript objects that look like this: {["186,2017"]} My goal is to extract and display only the values: 186, 2017 Initially, I attempted to use JSON.stringify thinking it was a JSON: console.log(JSON.stringify(data)); However, thi ...

Discovering hospitals in the vicinity with the help of Google Maps API and JavaScript

var MapApiApplication = { myCurrentPosition : "", mapOptions : "", marker : "", initialize : function(){ MapApiApplication.myCurrentPosition = new google.maps.LatLng(10.112293000000000000, 76.352684500000010000); M ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

unable to save the information to mongoDB

I've been attempting for the past 3 hours to save data from an HTML form to MongoDB using Node.js. When I click submit, it redirects to another page displaying the submitted data in JSON format, but it's not getting stored in the database. Here ...

The enigmatic dance of Angular and its hidden passcodes

Recently, I've been diving into learning Angular 2 and I'm exploring ways to safeguard the data in my application. I'm curious about how one can prevent data from being accessed on the front end of the app. Could serving the angular app thr ...

Leverage AJAX to transmit a PHP array to an external JavaScript file

I have a situation where I need to transfer an array from a PHP file to an external JavaScript file. My approach involves using AJAX as it appears to be the most suitable method for achieving this. However, when I try to use echo json_encode($exif), the JS ...

Error encountered with default theme styling in Material-UI React TypeScript components

Currently, I am working on integrating Material-UI (v4.4.3) with a React (v16.9.2) TypeScript (v3.6.3) website. Following the example of the AppBar component from https://material-ui.com/components/app-bar/ and the TypeScript Guide https://material-ui.com/ ...

SVG with embedded fonts failing to display properly in web browsers

Within this SVG, there are two different font types being used: SymbolMT for the mathematical expressions and Hind-Light for the text. Both fonts have been defined within the @font-face section of the SVG. The font used for the math expressions appears a ...

What is the best way to create an interactive menu icon that includes dropdown options using MUI menu features?

i am looking to create a component similar to this https://i.sstatic.net/fwIB0.png currently, I am utilizing a material UI pop menu in my project below is the JSX code snippet <div className="navMenu" style={{ position: "relative" ...

Struggles encountered while configuring React

I'm in need of assistance with setting up React, even though I have both Node and npm installed. When I enter the following command: npx create-react-app new-test-react --use-npm I encounter the following error message: npm ERR! code ENOTFOUND npm E ...

Showcased a few items from the model.forms dataset

My table has three fields: id, name, status. When I use {{ form|bootstrap }}, all fields are displayed. The 'name' field is a drop-down in HTML. I only want to show entries where the status is equal to 1. How can I achieve this? ...

Issues encountered when implementing server-sent events in a project built with Node.js and React

I've been working on implementing server-sent-events into my Node.js and React application. After doing some research and following tutorials online, I found this particular site to be very helpful and straightforward. The main objective is to have a ...

Why Am I Still Getting a 431 (Request Header Fields Too Large) Error in My React App Despite Clearing

Whenever I try to run a post request in my React app, I encounter the "431 (Request Header Fields Too Large)" error and I'm unable to identify the cause. Is there anyone who can assist me with this problem? I've attempted various solutions based ...

After a group of floated items, there will be an automatic "clear: both" applied

Within my Content Management System, I have custom Elements that need to be floated next to each other. Instead of adding an extra div with a class of "clear", I want to automatically insert a clear: both at the end using CSS3. I attempted this workaround ...

Is it possible to incorporate a 960 grid system into a div container?

Can I contain an entire 960 grid within a div on my webpage? I am looking to create a page wider than 960px, and considering placing sidebars outside of the 960 grid while having it manage the central column. ...