Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover.

Snippet of the current code:

import React from 'react';

const Contact = (props) => {
  const array = Object.entries(props);
  
  const classes = document.getElementsByClassName('btn');
  
  const display = (isShown) => {
    if (isShown) {
      for (let i =0; i < classes.length; i++) {
        classes[i].style.display = 'block';
      }
    } else {
      for (let i=0; i < classes.length; i++) {
        classes[i].style.display = 'none';
      }
    }
  };
  
  return (
    <table className="table table-light">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">Name</th>
                <th scope="col">Continent/Country</th>
                <th scope="col">eMail</th>
                <th scope="col">FreeGuyz</th>
                <th scope="col">Instagram</th>
                <th scope="col">Twitter</th>
            </tr>
        </thead>
        <tbody>
            {array.map((contact, index) => (
                <tr onMouseEnter={() => { display(true); }} onMouseLeave={() => display(false);} key={index}>
                    <th scope='row'>{index += 1}</th>
                    <td>{contact[1].name}</td>
                    <td>{contact[1].continentAndCountry}</td>
                    <td>{contact[1].email}</td>
                    <td>{contact[1].accountNameForFreeGuyz}</td>
                    <td>{contact[1].accountNameForInstagram}</td>
                    <td>{contact[1].accountNameForTwitter}</td>
                    <td>
                        <button style={{ marginRight: 5 + 'px' }} className='btn btn-warning' id={contact.id}>Edit</button>
                        <button className='btn btn-danger' id={contact.id} type='submit'>Delete</button>
                    </td>
                </tr>
            ))}
        </tbody>
    </table>
  );
};

export default Contact;

If anyone can help troubleshoot this issue, it would be greatly appreciated.

Answer №1

If there isn't a specific reason for using JavaScript, I would suggest utilizing CSS to address these types of issues. Ensure that you can target the edit button (for example, by assigning it a class of edit):

tr button.edit {
  display: none;
}

tr:hover button.edit {
  display: initial;
}

Answer №2

Here's my idea:

To improve the efficiency, consider creating individual components for each table row.

Within each component, establish a state variable to track the hover status using isHovered.

Toggle this state based on the mouseenter and mouseleave events.

const TableRow = ({ data, index }) => {
  const [isHovered, setHovered] = useState(false);
  
  // additional logic here
  
  return (
    <tr
      onMouseEnter={() => {
        setHovered(true);
      }}
      onMouseLeave={() => {
        setHovered(false);
      }}
      key={index}
    >
      <th scope="row">{(index += 1)}</th>
      <td>{data.name}</td>
      <td>{data.continentAndCountry}</td>
      <td>{data.email}</td>
      <td>{data.accountNameForFreeGuyz}</td>
      <td>{data.accountNameForInstagram}</td>
      <td>{data.accountNameForTwitter}</td>
      <td>
        {isHovered && 
          <>
            <button style={{ marginRight: 5 + "px" }} className="btn btn-warning" id={data.id}>
              Edit
            </button>
            <button className="btn btn-danger" id={data.id} type="submit">
              Delete
            </button>
          </>}
      </td>
    </tr>
  );
};

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

How to manually trigger the ajaxLoader feature in Tabulator version 3.5

Currently, I am working with version 3.5 of Tabulator from . When populating the table using an ajax request, a "loading icon" is displayed during the loading process. Prior to executing the ajax request for Tabulator, I perform some preliminary check op ...

Animated mosaic pattern menu design

Is there a way to achieve this effect with a sketch? Note: I would like to add hover animation to the borders if possible. I attempted to do it using the following code: clip-path: polygon(0 0, 100% 0, 92% 86%, 6% 100%); However, the shapes created by ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

Utilizing Node.js to create a REST API that allows for seamless communication with a MongoDB database through

Currently, I am developing a web application utilizing the MERN framework (MongoDB, Express, Node.js for back-end, React for front-end). One specific part of my web application requires frequent access to a collection in the MongoDB database (every 50 ms) ...

Installing dependencies for Material-UI using npm

I just started my React and NPM journey. After setting up a new directory, running npm init, and then npm install to install React, here is how my configuration in package.json looks like: { "name": "reactapp", "version": "1.0.0", "description": "", ...

When the drawer is opened, there is a strange phenomenon of all buttons being mysteriously clicked

Currently, I am working on a single-page web application utilizing React and Material UI, along with React-Mini-Router for routing. The app features a side drawer that is activated by clicking a hamburger icon located in the top app bar. Each item in the d ...

The submit button fails to produce any result

I have a submit button in a contact form that triggers PHP code to send an email. However, when I press the button nothing happens - not even the PHP code is displayed as it should be if PHP were not installed. Interestingly, I have tested other simple mai ...

Exploring Angular: How does Number.isNaN handle non-empty strings?

Within my component, there is a dropdown menu that allows users to choose a value. Upon selecting an item from the dropdown, a function called onDropdownChange is triggered. The parameter passed to this function can either be a string ("Please select an op ...

Automatically notifying users via email about console errors in JavaScript

My exploration on this question and useful links: How to send console messages and errors to alert? jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined The coding example: function handleError(evt) { if (ev ...

Prevent discrepancies between the outcome on the server and the client side

My website utilizes a combination of PHP and JavaScript for processing results - some server-side, some client-side. Solely relying on JavaScript can cause issues with search engine crawling, while using only PHP may not provide real-time responses accura ...

One way to position a sidebar between two divs is to ensure it adjusts seamlessly to the size of the browser window when resized

In my layout, I have two grids: one for the header and one for the footer. In between these two grids, I am using a sidebar on the left side. Below is the JavaScript code I am using: function adjustSize() { var heights = window.innerHeight; docum ...

How can jQuery determine if multiple selectors are disabled and return true?

I am currently working on a form in which all fields are disabled except for the "textarea" field. The goal is to enable the "valid" button when the user types anything into the textarea while keeping all other inputs disabled. I initially attempted using ...

"Utilizing JSON data to implement custom time formatting on the y-axis with AmCharts

Looking to convert minutes to hh:mm:ss format in my JavaScript code var allDataTime = [{ date: new Date(2012, 0, 1), "col": "LONG CALL WAITING", "duration1": '720', "duration2": '57', "duration3": ...

Tips on utilizing multiple instances of ReactPixel.track('abc') within a single component:

I need to add two ReactPixel.track('abc') and ReactPixel.track('cba') on a component. Should I include one ReactPixe.init('id') or two? Here is an example of the code: componentDidMount() { const options = { autoConfig: ...

Is it possible to upload an image file while the element is hidden with "display: none" property?

I need to upload a file using Selenium webdriver. Here is the URL of the page. <div class="async-upload__thumb item-image__area"> <div class="fab-dialog__thumb-drop-zone async-upload__thumb-drop-zone"> <p class="async-upload__thumb-ms ...

A comprehensive guide on utilizing the loading.tsx file in Next JS

In the OnboardingForm.tsx component, I have a straightforward function to handle form data. async function handleFormData(formData: FormData) { const result = await createUserFromForm( formData, clerkUserId as string, emailAddress a ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...

The align-items property in Flexbox is not functioning as expected when applied to Link components contained within

I'm in the process of creating a simple navigation bar using flexbox, but I'm encountering an issue where the content within the unordered list is not vertically centered. Below is the HTML code snippet: *,*::before,*::after{ margin: 0; ...

Erroneous Marker Placement Detected

Here is the data from my DataTable: Country Types of sales Total sales($) Name State United states of America chemicals 12662871 Obama GA Unite ...