Utilizing React to highlight buttons that share the same index value upon hover

I have some data in a JavaScript object from a JSON file, where certain entries have a spanid (number) while others do not. I've written React code to highlight buttons with a spanid on hover, but I'm looking for a way to highlight or change the background color of all buttons with the same spanid when one is hovered. Buttons without a spanid should not be highlighted. Any suggestions on how to achieve this?

App.css

.example_c {
  color: #494949 !important;
  text-transform: uppercase;
  text-decoration: none;
  background: #ffffff;
  padding: 10px;
  border: 2px solid #494949 !important;
  display: inline-block;
  transition: all 0.4s ease 0s;
  margin-left:10px;
  margin-top:10px;
  width:120px;
}

.example_c:hover {
  background: #556bce;
  color: white !important;
}

.example_d {
  color: #494949 !important;
  text-transform: uppercase;
  text-decoration: none;
  background: #ffffff;
  padding: 10px;
  border: 2px solid #494949 !important;
  display: inline-block;
  transition: all 0.4s ease 0s;
  margin-left:10px;
  margin-top:10px;
  width:120px;
}

App.js

import React from 'react';
import './App.css';
import Records from "./records.json";
class Relation extends React.Component {


  render () {
     const tokens_to_render = [];
     const input_tokens = Records;

     var cntr = 0;

     input_tokens.forEach(tk => {
         const span = tk['spanid'];
         if (!tk['spanid']) {
             tokens_to_render.push(
                 <button key={cntr} index={tk['spanid']} className='example_d'> 
                     {tk['token_text']} 
                </button>
            )
            cntr = cntr + 1;
         } else {
  
            tokens_to_render.push(
                <button key={cntr} index={tk['spanid']} className='example_c' > 
                    {tk['token_text']} 
                </button>
            )
            cntr = cntr + 1;
         }
    });
  
    return (
        <div className="control-box">
           {tokens_to_render}
        </div>
    )
  }
}

export default Relation;

Answer №1

It is recommended to utilize the mouseover and mouseout events in order to establish a state for the hovered spanid. By comparing this state with other buttons during re-rendering, you can highlight those that require attention:

const Items = [
  {
    spanid: 'foo',
    token_text: 'Identical',
  },
  {
    spanid: 'bar',
    token_text: 'Different',
  },
  {
    spanid: 'foo',
    token_text: 'Similar foo',
  },
  {
    token_text: 'Baz',
  },
];

class Relationship extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hovered: null,
    };
    
    this.unsetHover = this.unsetHover.bind(this);
  }
  
  setHover(id) {
    return () => {
      this.setState({ hovered: id });
    }
  }
  
  unsetHover() {
    this.setState({ hovered: null });
  }
 
  render () {
     const items_to_render = [];
     const input_items = Items;

     var counter = 0;

     input_items.forEach(item => {
         const span = item['spanid'];
         if (!item['spanid']) {
             items_to_render.push(
                 <button key={counter} index={item['spanid']} className='example_d'> 
                     {item['token_text']} 
                </button>
            )
            counter = counter + 1;
         } else {
  
            items_to_render.push(
                <button
                  key={counter}
                  index={item['spanid']}
                  className={`example_c ${item.spanid === this.state.hovered && 'example_c-hovered'}`}
                  onMouseOver={this.setHover(item.spanid)}
                  onMouseOut={this.unsetHover}
                > 
                    {item['token_text']} 
                </button>
            )
            counter = counter + 1;
         }
    });
  
    return (
        <div className="control-box">
           {items_to_render}
        </div>
    )
  }
}


ReactDOM.createRoot(document.getElementById('app')).render(<Relationship/>);
.example_c {
  color: #494949 !important;
  text-transform: uppercase;
  text-decoration: none;
  background: #ffffff;
  padding: 10px;
  border: 2px solid #494949 !important;
  display: inline-block;
  transition: all 0.4s ease 0s;
  margin-left:10px;
  margin-top:10px;
  width:120px;
}

.example_c-hovered,
.example_c:hover {
  background: #556bce;
  color: white !important;
}

.example_d {
  color: #494949 !important;
  text-transform: uppercase;
  text-decoration: none;
  background: #ffffff;
  padding: 10px;
  border: 2px solid #494949 !important;
  display: inline-block;
  transition: all 0.4s ease 0s;
  margin-left:10px;
  margin-top:10px;
  width:120px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div id="app"></div>

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

Three responsive images neatly arranged within separate div containers

Looking to have these 3 divs align horizontally with responsive images. Having trouble maintaining the layout when setting max-width. Any suggestions? .fl { display: flex; flex-wrap: no-wrap; height: 35%; flex-direction: row; } .pic { width: ...

How can you execute PHP code within another PHP script without triggering a redirect?

I'm faced with a situation where I have two php files, namely abc.php and def.php. My goal is to only display abc.php in the browser URL bar when it executes. Additionally, upon clicking the submit button on my HTML page, abc.php should be triggered t ...

Managing visibility of boxes in child components using React and Material UI

Currently in my parent class, I have the following code snippet: ... return ( <div className={prefix}> {(toEditBooking===true ? <EditBooking editBooking={true} booking={selected}/> : null)} <Paper style={header} rounded={f ...

This function named error is implemented in native code

My website is built in C# using asp.net. When the Onchange() event is triggered on the Dropdownlist, I call this jQuery function which displays an error: function error(){[native code]} <script type="text/javascript"> function GetDescription ...

What is the best way to accurately measure the distance between two points on a 360 image using A-Frame technology?

Is there a way to accurately measure the distance between two points in a 360 picture of an interior using the a-frame.io framework? We attempted converting the unit system of a-frame to centimeters and used two points with known dimensions as a reference ...

What are the steps to launch a Next.js application on cPanel hosting?

Currently, I am faced with the task of deploying a Next.js application on cPanel. Node and npm have been successfully installed. Could you kindly guide me on how to deploy the Next.js app using this configuration? In my attempt to build the app in the cPa ...

The iframe is being loaded in the center of the page rather than at the top

I am currently facing an issue with embedding wetransfer into a website using iframe. The problem is that when the page loads, it automatically scrolls past the header section of the site instead of loading the new page at the top. How can I prevent this ...

The NgFor is unable to iterate over an array because it is being treated as an

When attempting to call a new endpoint for displaying data, I noticed that the previous set of data is wrapped with an extra pair of brackets '[]', which seems to be causing a problem. The new endpoint does not format the data in this way when I ...

The compiled JavaScript is getting messed up by the Grunt build process

I have taken over a project that was incomplete from the beginning. I am facing issues with the deployment as the grunt task is not working correctly, even after following the overrides specified here. The generated vendor.js file seems to be causing error ...

Arranging the columns of a matrix

My dilemma involves a matrix (or multidimensional array) filled with non-unique values, similar to this example: var matrix = [ [1, 3, 2, 4, 1], [2, 4, 1, 3, 2], [4, 3, 2, 1, 4] ] I am in need ...

contrasting the practice of dispatching a function or action with the act of dispatching an object

When using the store.dispatch(...) We have the option to utilize it in two ways: store.dispatch(dispatch => { dispatch(someOtherAction()) }); or we can alternatively do this: store.dispatch({type: constants.X}) Question one: What are the names ...

Using various functions for event listeners

Avoiding jQuery Hello there! I'm currently working on implementing multiple Event Listeners for a button. function logoContame(){ var logo = document.getElementById("logoheader"); logo.addEventListener("click", hideDivHistorias) ...

The initial click event for the input element in Jquery is not functioning correctly

I found a jQuery date selector online and the script looked something like this... <script type="text/javascript> $(document).ready(function () { $("#date3").click(function() { $("#date3").scroller({ preset: 'datetime' }); wheels = []; whe ...

Combine an array nested within an object with each key of the object

Alright, let's dive into the structure of these objects: custom_fields:{ 21:{ edit:true required:true show:true } } In my Angular controller, this object is stored under $scope.page.custom_fields. Within this object, there is another ...

What is the best way to asynchronously load an external javascript file in a popup.html file?

I have successfully implemented all the necessary functionalities, but I noticed a delay in loading the popup.html after adding an external javascript file. This file is only a few lines long, so the delay is quite frustrating. To eliminate this lag, I be ...

A different approach in React for transitioning to a specific route using react-router-dom version 4.1.1 in a

While experimenting with the react-router-dom alpha, I came across the 'transitionTo' method for route changes. However, it appears to have been removed in version 4.1.1. I am now wondering what would be the best alternative for achieving the sam ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Converting a single 10GB zip file into five separate 2GB files with the help of NodeJS

var fs = require('fs'); var archiver = require('archiver'); var output = fs.createWriteStream('./test.zip'); var archive = archiver('zip', { gzip: true, zlib: { level: 9 } // Sets the compression level. }); ...

How to show an Info Window on multiple coordinates using an arcgis map in a Next JS application

Here is my latest JS code for showcasing a basic ArcGIS map with markers located at specific coordinates. Could someone please advise me on how to implement popups/Info windows for the markers on the map? For example, when I click on a marker, it should d ...

Animate my banner images only after they have fully loaded using Jquery

I recently came across a banner image slideshow in jQuery, but it seems to be animating even before the images are fully loaded. This results in the slideshow displaying image descriptions without the actual images themselves. Can anyone help me modify th ...