ReactJS does not update the conditional CSS class when hovering with mouseOnEnter or mouseOnOver

I am currently attempting to showcase data in a table where each row features an info icon that is only visible upon hovering. Additionally, I want a pop-up to appear when the info icon is clicked (there is an onclick function assigned to this button).

Here's a snippet of the code I've written for this purpose:

<td className="reportCard">
   {filteredVehicles.map(t =>
    <tr className="cardList" onMouseEnter={() => this.onClickReportRow(t.reportId) }>
          <span className="CardReportsName"><p className="reportNameP" >{t.reportName}</p></span>
          <span style={PreviewBtn} className={this.selectedReportId == t.reportId ? "previewBtnDisplayBlock" : "previewBtnDisplayNone"}>
                 <em className="fa fa-info" aria-hidden="true" onClick={() => this.showPopUp()} />
             </span>
        </tr>
       )}
      </td>

 onClickReportRow(reportId){
        this.selectedReportId= reportId
    }

Unfortunately, even though the hover event is triggered when I hover over a row, the conditional class does not change as expected. It seems to work fine if I use onclick, but when combined with Font Awesome's onclick, it fails to update the class.

This problem is quite perplexing and I'm unsure about the root cause.

Thank you in advance.

Answer №1

Identified Issue: The issue lies in this line of code: this.selectedReportId == t.reportId

Resolution: It appears that this.selectedReportId is not a function, but rather a variable. To properly compare the reportId, you need to create a state that can be updated on mouseEnter or Leave events. This will allow you to accurately track and modify the selectedReportId.

Helpful Link:Visit this link for more details

import React, { Component } from "react";
import "./styles.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCoffee } from "@fortawesome/free-solid-svg-icons";
const element = <FontAwesomeIcon icon={faCoffee} />;
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      filteredVehicles: [
        {
          reportId: 1,
          reportName: "One"
        },
        {
          reportId: 2,
          reportName: "TWO"
        }
      ],
      selectedReportId: null,
      popUp: false
    };
  }
  onClickReportRow = (ID) => {
    this.setState({ selectedReportId: ID });
  };
  showPopUp = () => {
    this.setState({ popUp: !this.state.popUp });
  };
  handleonMouseLeave = () => {
    this.setState({ selectedReportId: "" });
  };
  render() {
    return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <table>
          <td className="reportCard">
            {this.state.filteredVehicles.map((t) => (
              <tr
                className="cardList"
                onMouseEnter={() => this.onClickReportRow(t.reportId)}
                onMouseLeave={() => this.handleonMouseLeave()}
              >
                <span className="CardReportsName">
                  <p className="reportNameP">{t.reportName}</p>
                </span>
                <span
                  className={
                    this.state.selectedReportId === t.reportId
                      ? "previewBtnDisplayBlock"
                      : "previewBtnDisplayNone"
                  }
                >
                  {element}
                </span>
              </tr>
            ))}
          </td>
        </table>
        {this.state.popUp ? (
          <div
            class="modal fade"
            tabindex="-1"
            role="dialog"
            aria-labelledby="exampleModalLabel"
            aria-hidden="true"
          >
            Required PopUp
          </div>
        ) : null}
      </div>
    );
  }
}

export default App;

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

Guide to implementing input fields in a form in React.js when the user chooses the "Other" option from a dropdown menu

For my project, I have implemented a multi-select dropdown input feature that saves all selected items in a useState array when the user clicks on the add icon. However, I am facing an issue where I need to render an input field only when the "Other" optio ...

Issues with IE 11: SVG Map Not Triggering Mouseenter or Mouseleave Events

I've been grappling with this issue for the past couple of days and despite trying numerous solutions, nothing seems to be working. My SVG map of the US has jQuery mouseenter and mouseleave events that function properly in browsers other than IE 11 ( ...

What are the steps for effectively utilizing the EmChart to achieve precise font sizes in ems?

Can you explain the intended use of this chart and instructions for how to utilize it? ...

Warnings from Webpack may appear while running the Next.js development server

Encountering these warnings when running npm dev: <w> [webpack.cache.PackFileCacheStrategy] Restoring pack from /Users/pdeva/code/monorepo/web/app/.next/cache/webpack/client-development.pack failed: TypeError: Cannot read properties of undefined (rea ...

VSTS is having a sluggish performance when running the npm build process

My React app was created using create-react-app and then ejected to include custom webpack configuration for optimized code splitting. While the app builds fine on my local machine with npm run build, it takes too long to build during the VSTS build proces ...

Using multiple conditions in an angular ngif statement to create a variable

Is it possible to assign the result of a function to a variable in Angular (13) within the .html section of a component, specifically with multiple conditions in ngIf? <div *ngIf="let getMyVar() as myVar && isVisible && isClean" ...

Ways to prevent body content from overlapping with footer content and appearing below

Currently, I am utilizing an autocomplete text box where the scroll bar exceeds based on dynamic values. However, if more values are displayed in the text box, the scroll bar automatically extends to exceed the footer of the page, resulting in two scroll b ...

Adjust the height of the div container and implement a vertical scroll feature on the fixed element

I created a fiddle and was hoping to enable scrolling, but I have been unable to find a solution. http://jsfiddle.net/sq181h3h/3/ I tried both of these options, but nothing seems to be working: #league_chat { overflow-y:scroll; } #league_chat { ...

JS custom scrollbar thumb size issues in relation to the scroll width of the element

I recently implemented a custom scrollbar for a component on my website. To determine the length of the scrollbar thumb, I use the formula viewportWidth / element.scrollWidth;. This provides me with a percentage value that I then apply to the thumb elemen ...

Utilizing the Pub/Sub architecture to integrate the kafka-node library within Node Js

Utilizing the kafka-node module in my NodeJs Microservise project, I am aiming to implement a Pub/Sub (publisher and subscriber) design pattern within the Functional programming paradigm. producer.js const client = new kafka.KafkaClient({ kafkaHost: ...

How can I retrieve the selected value from an Angular 2 dropdown menu when it changes, in order to utilize it within a function?

I am currently working on creating a dropdown menu with multiple options. When a user selects an option, I need to make an API call that requires an ID parameter. Inside my component.ts file, I have defined an array containing the values like this: valu ...

Sentry alert: Encountered a TypeError with the message "The function (0 , i.baggageHeaderToDynamicSamplingContext) does not

My website, which is built using Next.js and has Sentry attached to it, runs smoothly on localhost, dev, and staging environments. However, I am facing an issue when trying to run it on my main production server. The error message displayed is as follows: ...

Problem with React Material UI syled-engine resolution inconsistency during test execution (Functions properly during serve/build process)

Currently, I am utilizing Material UI components from mui.com with styled-components instead of the default emotion library. I have made changes to my tsconfig.json file to include: "compilerOptions": { ..., "paths": { .. ...

What is the best method to implement a loading spinner within a React and Node application while using Nodemailer?

Is it possible to implement a functionality where clicking the Send button triggers a spinner next to the button, followed by changing the button text to "Message Sent"? I managed to change the button text, but there is no loading time, it happens instantl ...

Utilizing Javascript for logging into Facebook

Feeling frustrated! I've been struggling to implement the Facebook Login pop-up on my website using the Facebook JavaScript API. Despite following tutorials, I can't seem to make the login pop-up appear. Instead, when I go through the login pro ...

The PHP on server could not be loaded by Ajax

Trying to establish a PHP connection, encountering an error and seeking assistance. The error message displayed is as follows: { "readyState": 0, "status": 0, "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpReq ...

Any tips on making Angular 8's sort table function seamlessly integrate with data retrieved from Firebase?

I am currently working on an angular PWA project that utilizes a material table to display data from Firebase. The data is being shown properly and the paginator is functioning as expected. However, I am facing an issue with sorting the data using mat-sort ...

Form submission is not possible while the login form is active

I'm encountering an issue where I am unable to trigger - ng-submit or ng-click on this code except for the local onclick function on the login button. If you have any insights or solutions, please share them: <form ng-submit = "login.submitLogin ...

Can an array be generated on-the-fly with objects contained within it?

Seeking advice on looping through an array of objects to achieve a specific result. Here is the initial array: var testArray = [{'name':'name1', 'xaxis':'xaxis1', 'yaxis':'yaxis1'}, ...

Utilizing Bootstrap to arrange table cells in a shifted manner

I'm new to utilizing bootstrap in web development. I've been exploring various examples of bootstrap templates that include tables, and I noticed that when I resize my browser window, the table adjusts accordingly. Now, I'm curious to know ...