Attempting to change the background color of a table row when hovering in React, but experiencing no success

Describing the appearance of my table row:

<tr
    onMouseEnter={() => {this.buttonIsHovered = true} }
    onMouseLeave={() => {this.buttonIsHovered = false}}
    className={this.buttonIsHovered ? 'hover' : null}>

The initial value of buttonIsHovered is false. The .hover class in CSS is defined as:

.hover {
  background-color: aqua
}

Even though I've imported the CSS successfully, the hover effect doesn't seem to work. Does anyone have any suggestions? Your help is appreciated, thank you!

Answer №1

Check out this sample that showcases exactly what you're looking for:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    red: false
  };

  toggle = () => {
    this.setState({ red: !this.state.red });
  };

  render() {
    return (
      <React.Fragment>
        <h1
          onMouseEnter={this.toggle}
          onMouseLeave={this.toggle}
          style={{ background: this.state.red ? "red" : "" }}
        >
          Hover me!
        </h1>
      </React.Fragment>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

You can view the live example on CodeSandbox here.

Answer №2

Hey there! Just tried out this code snippet and it worked like a charm.

    class Application extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      background: 'white'
    }
    this.changeBackground = this.changeBackground.bind(this);
    this.resetBackground = this.resetBackground.bind(this);
  }

  changeBackground(){
    this.setState({background:'blue'})
  }

  resetBackground(){
    this.setState({background:'white'})
  }

  render() {
    return (
      <div className="Application">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <table>
            <tbody>
              <tr onMouseEnter={this.changeBackground} onMouseLeave={this.resetBackground} style={{backgroundColor:this.state.background}}><td>Hello World</td></tr>
            </tbody>
          </table>
        </header>
      </div>
    );
  }
}

export default Application;

Answer №3

To modify the color, you can utilize CSS styling:

const styles = theme => ({ 
 button: {
  margin: '15px 0',
  color: '#fff',
  borderRadius: '5px',
  backgroundColor: '#fff',
  '&:hover': {
    backgroundColor: '#999',
  },
 },
})

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

A guide on incorporating the CSS 'content' property with the 'option' tag

Is it possible to include CSS 'content' in the 'option' tag? For example, I want to display "Name: Volvo". <html> <head> <style> option:before { content: "Name: "; } </style> </head> <body> ...

Incorporating XMLHttpRequest in my React Typescript App to trigger a Mailchimp API call, allowing users to easily sign up for the newsletter

My website needs to integrate Mailchimp's API in order for users to subscribe to a newsletter by entering their email into a field. I am looking to implement this without relying on any external libraries. To test out the functionality, I have set up ...

The Grid within the Container is presented vertically rather than horizontally

I followed the coding style exactly as shown in a recent tutorial on YouTube, where the cards were displayed in a row. However, when I implemented it, they are appearing strangely in a column. Why is this happening? The default should be inline. Even afte ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

New to CSS Media Queries? Discover the Correct Way to Define Element Height!

Sorry for the oversized images! I'm diving into media queries for the first time. When I adjust my browser window to 320px, here's how my site displays: This is what I want it to look like on mobile phones. However, when I view it on my iPhone, ...

Switching the image on click of an option tag

I'm looking to create a dynamic image changing feature using two select tags in my HTML. One select tag is for the model and the other is for the color. When a user selects a model from the first dropdown, I want the image to change to reflect that mo ...

What is the best way to utilize mapping and filtering distinct values in an array using TypeScript?

What is the best way to filter and map distinct elements from an array into another array? I've experimented with various methods but keep encountering a syntax error stating "Illegal return statement". My objective is to display only unique items f ...

jQuery - Event cannot be triggered on the 'deselect' or 'focusout' of <option> tag

Check out the demo here Hello there, I have a situation where I need an input box to appear below a select option, only if the user selects "Other". The code currently uses the .click() function on the option, but now I am trying to make the input box di ...

Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this: let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxChunkLength = 3; I am looking to divide this array into multiple arrays as follows: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, ...

React Div Element Not Extending to Web Page Margin

creating white space between the green div and both the top and sides of the screen This is my index page export default function Home() { return( <div className = {stylesMain.bodyDiv}> <div>home</div> &l ...

The Facebook share button on my website is malfunctioning

Could someone please help me figure out why my custom Facebook share button is not functioning properly? When I click the button, the share window fails to appear. I have tested it as an html file on a live web server and have thoroughly reviewed the Faceb ...

Using AJAX with Rails to add data to multiple items in a one-to-many association

In my Rails application, I have set up a one-to-many association where a Song has many Channels, and each Channel belongs to a Song. The challenge I am facing is when trying to create a new Song with 6 Channels. Below is a snippet of the form in the fronte ...

Blurry text issue observed on certain mobile devices with Next.js components

There continues to be an issue on my NextJS page where some text appears blurry on certain mobile devices, particularly iPhones. This problem is only present on two specific components - both of which are interactive cards that can be flipped to reveal the ...

Every time I hit the play button on my video player, it starts playing multiple videos simultaneously on the same page

I'm having an issue with customizing a video player in HTML5. When I press play on the top video, it automatically plays both videos on the page simultaneously. For reference, here is my code on jsfiddle: http://jsfiddle.net/BannerBomb/U4MZ3/27/ Bel ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Why is there an issue with the JavaScript array when accessing data['sax']?

There seems to be some confusion regarding the contents of this array and how it assigns values to the variable set. It would be greatly appreciated if someone could provide an example pertaining to the usage of data['sax']. Additionally, an expl ...

Automatically populate form fields with data from the clicked row in the HTML table when using JSP

Attempting to populate form fields using jQuery or JavaScript with row elements selected by clicking on the row. Tried a solution from Stack Overflow that didn't work as expected. I'm new to this, so please bear with me. (http://jsbin.com/rotuni/ ...

Select a random object from a document and dispatch it. A Discord bot

I'm looking to enhance my bot by adding a command that retrieves a random quote from a JSON file and displays it in chat. I've already figured out how to do this using an array, but I'm not sure how to pull the quotes from a file. EDIT: ...

Having trouble with my Bootstrap 4 navbar button - what am I doing wrong?

After conducting research online, I found myself unable to resolve my issue due to my lack of proficiency in English. I apologize for any confusion caused and would like to revisit the topic. The problem lies with my navbar toggle that is not functioning ...

Navigating through nested JSON objects in React to display data effectively

I have been struggling for hours to find a solution to this problem with no success. I really need your assistance. The task at hand involves looping through a JSON file and creating a user interface that consists of multiple columns, each containing vari ...