React components are graced with a clear icon that is visible on every element

I'm attempting to show a remove icon on a grid display when the user hovers over it with their mouse.

this.state = {
      action: [],
}
<div>
    {this.state.action.map((value, index) => {
    return (
    <div key={index} onMouseEnter={this.removeElementIcon} onMouseLeave={this.hideRemoveElementIcon} className={classes.gridClass}>
        <Grid className={classes.marginGrid}>
            <Paper className={classes.paddingPaper}>
                <Typography variant={"h5"}>{value}</Typography>
                <Typography component={"p"}>{value}</Typography>
            </Paper>
        </Grid>
        {this.state.removeElementIcon ?
        <IconButton className={classes.removeElement} color={"secondary"} arial-label={"remove element"} onClick={()=> this.removeElement(value)}>
            <ClearIcon color={"error"} />
        </IconButton>
        : null}
    </div>

I have experimented with returning some jsx directly from the method itself.

removeElementIcon = () => {
  return ({
      this.state.removeElementIcon ?
      <IconButton className={classes.removeElement} color={"secondary"}
                        arial-label={"remove element"} onClick={() => this.removeElement(value)}>
              <ClearIcon color={"error"}/>
            </IconButton> :
          null
  });

Instead of:

removeElementIcon = () => {
    this.setState({removeElementIcon: true});
};

hideRemoveElementIcon = () => {
    this.setState({removeElementIcon: false});
};

Rather than only displaying the clear icon on a single element, it appears on all elements simultaneously.

Answer №1

To ensure smooth functioning, it is crucial to keep track of the item's index in the state,

this.state = {
   action: [],
   hoverIndex: '',
}

Make sure to pass the index parameter to your removeElementIcon function,

<div 
   key={index} 
   onMouseEnter={() => this.removeElementIcon(index)}
   onMouseLeave={hideRemoveElementIcon} 
   className={classes.gridClass}
>

   ...
</div>

Within your function, set the hoverIndex,

removeElementIcon = (index) => {
    this.setState({removeElementIcon: true, hoverIndex: index});
};


hideRemoveElementIcon = () => {
    this.setState({removeElementIcon: false, hoverIndex:''});
};

Lastly, implement the condition,

{this.state.removeElementIcon && this.state.hoverIndex === index ?
    <IconButton className={classes.removeElement} color={"secondary"} arial-label={"remove element"} onClick={() => this.removeElement(value)}>
        <ClearIcon color={"error"}/>
    </IconButton>
    : null
}

Alternatively, you can use a more concise approach,

{this.state.removeElementIcon && this.state.hoverIndex === index &&
    <IconButton className={classes.removeElement} color={"secondary"} arial-label={"remove element"} onClick={() => this.removeElement(value)}>
        <ClearIcon color={"error"}/>
    </IconButton>
}

Check out this Demo for a simple button example.

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 extracting information from a JSON response with the fetch API

Issue trying to display JSON response after API call using fetch. Response visible in Chrome's response tab, but not found in fetch response object. Client side import React from 'react'; import './App.css'; class App extends ...

Error: Attempting to access the 'SearchBox' property of an undefined variable is not allowed

I have been working on a Google Maps code that displays both public and private schools with different markers for each category. However, when running the code, I encountered an error specifically on this line of code: var searchBox = new google.maps.pl ...

How can I use lodash to iterate through and remove whitespace from array elements?

I am currently working on a project involving demo lodash functionality, and I have encountered some unexpected behavior. Within an array of cars, there are various non-string elements mixed in. My goal is to iterate through each element of the array, rem ...

Making a POST request across domains without relying on any third-party frameworks

Is it possible to create a cross-domain request using vanilla JavaScript without relying on frameworks like jQuery? I am looking to send a JSON to a service on a different domain and receive the response using a callback function. Can this be done solely ...

What is the best way to save the city name received from geolocation into a variable and then make an AJAX request?

<script> new Vue({ el: '#fad' , data: { data: {}, }, mounted() { var self = this; navigator.geolocation.getCurrentPosition(success, error); function success(position) { var GEOCO ...

Arrangement of code: Utilizing a Node server and React project with a common set of

Query I am managing: a simple react client, and a node server that functions as both the client pages provider and an API for the client. These projects are tightly integrated, separate TypeScript ventures encompassed by a unified git repository. The se ...

I'm having trouble getting my .click method to work with the <div id=menuButton>. Can anyone help me figure out why this is happening?

Here is the HTML code I created for a dropdown menu. Initially, in the CSS file, the menu is set to display: none; <!doctype html> <html> <head> <title>DropDown Menu</title> <link rel="stylesheet" href="normalize ...

Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name: input type="text" id="demonum" size="05"> <button type="button" onclick="load_doc()">click</button><br><br> <input type="checkbox" id ="check" > The r ...

Pattern to identify a 32-character string comprising a mix of letters and numbers

I am in search of a JavaScript regex pattern that can identify strings with the following format... loYm9vYzE6Z-aaj5lL_Og539wFer0KfD pxeGxvYzE6o97T7OD2mu_qowJdqR7NRc gwaXhuYzE6l3r1wh5ZdSkJvtK6uSw11d These strings are always 32 characters long and conta ...

JavaScript function failing to properly handle PHP array input

I am facing an issue with a PHP array that I am trying to pass to a JavaScript function using "json_encode($array)". Every time I click the button to trigger the function, the page simply refreshes without any action being taken. I have attempted to troub ...

Can you explain the significance of the "table$aria-label" and "input$autocomplete" attributes in the context of Svelte SMUI?

As a newcomer to Svelte and SMUI, I recently explored the official documentation at . I encountered some peculiar attribute declarations like "table$aria-label" and "input$autocomplete". The usage of dollar signs in naming conventions as well as the prefix ...

What is the process for adding images from CSS (backgrounds, etc.) to the build folder with webpack?

Trying out the file loader for processing images and adding them to my build folder. Images within HTML files successfully show up in the build, but the ones from styles do not. I've divided my webpack configuration into two separate files and use t ...

What is the best way to have text wrap around an icon in my React application?

I am facing an issue while trying to display the note description over the trash icon in a React app. I have tried various methods but can't seem to achieve the desired effect. Can anyone guide me on how to get this layout? Here is what I intend to a ...

Is it possible for me to generate values using PHP that can be easily read by JavaScript?

I'm currently building a website and I am facing some challenges when trying to incorporate JavaScript for real-time calculations. Here are my issues: Is there a more efficient way to avoid manually typing out the code for each level up to 90, lik ...

When employing GraphQL Apollo refetch with React, the update will extend to various other components as well

My current setup involves using react along with Apollo. I have implemented refetch in the ProgressBar component, which updates every 3 seconds. Interestingly, another component named MemoBox also utilizes refetch to update the screen at the same int ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Guide on modifying values using both input fields and buttons at the same time

I am facing an issue with my input field that is designed to accept numbers. I want the value to be changed both via keyboard input and buttons. The buttons are functioning correctly unless I try to use keyboard input as well. For instance, if I enter 10 ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

necessity for a condition in Material UI input field

I need assistance with a function that I use to incorporate Material UI text fields into my code. The issue I'm currently facing is figuring out how to dynamically add the "required" attribute based on a boolean parameter that determines whether the f ...

The tab content in VerticalTab Material React UI is spilling out and overflowing

Having some trouble with this particular component. Whenever I input content larger than my Grid size, it overflows the VerticalTab section. You can see an example of this in this codesandbox. Here's what I've attempted: return ( <div cla ...