Why isn't the hover function working on the table row element?

When I try to apply a hover effect on tbody and td elements, it works perfectly. However, when I apply the same effect to the tr element, it doesn't work as expected. I am using inline style (js pattern) rather than CSS code and incorporating Radium into my project.

Below is an example of my code:

<tr key={id} style={styles.row} onClick={click}>
    <td style={stylestd}>
        <span style={styles.data}>asdc</span>
    </td>
</tr>

Here is how I have styled it:

row: {
    display: 'table-row',
    borderBottom: '1px solid #ddd',
    height: '20px',

   ':hover': {
        cursor: 'pointer',
        backgroundColor: 'red',
    },
},

Thank you.

Answer №1

Here is the solution to your problem, including the CSS code for a hover effect:

tr:hover{
  cursor: pointer;
  background-color:red;
}
 <table>
   <tr key={id} style="border 1px solid;" onClick={click}>
         <td>
            <span >asdc</span>
         </td>
  </tr>
  </table>

Answer №2

Your current inline styling style={styles.row} does not support the use of :hover. To enable hover effects, it's necessary to define the :hover rule explicitly in your CSS.


For more information on this topic, refer to this resource.

The pseudo-selector :hover only functions within the CSS stylesheet as it specifies the selection criteria. It doesn't have an equivalent for inline styles.

Alternatively, you can utilize onMouseOver and apply styles dynamically using this approach.

<tr key={id} style={styles.row} onClick={click} onMouseOver={hoverrule}>

An alternative solution is to explore the library Styled-components, which allows nesting of CSS with hover rules effortlessly.

Referencing an example from here:

import React from 'react';
import styled from 'styled-components';

const Div = styled.div`
  margin: 40px;
  border: 5px outset pink;
  &:hover {
   background-color: yellow;
 }
`;

const Paragraph = styled.p`
  font-size: 15px;
  text-align: center;
`;

const OutsetBox = () => (
  <Div>
    <Paragraph>Get started with styled-components 💅</Paragraph>
  </Div>
);

export default OutsetBox;

In this context, I haven't provided an example with the tr element since utilizing the Styled-components library may be unnecessary for implementing hover styles alone. However, if you believe adopting this library would enhance your project, feel free to experiment with this solution.

Answer №3

Try out this revised code for a successful outcome:

<tr key={id} style={styles.row} onClick={click}>
    <td style={stylestd}>
        <span style={styles.data}>asdc</span>
    </td>
</tr>

To implement hover effects, avoid using inline css and opt for internal or external css instead:

tr{
    display: table-row;
    border-bottom: 1px solid #ddd;
    height: 20px;
}
tr:hover{
    cursor: pointer;
    background: #red;
}

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

Error: Trying to use Router without providing a middleware function. Please make sure to pass a valid middleware function while using Router

While working on my express application with MongoJS, I encountered an issue where despite returning a function, it was showing that an object has been returned instead. To address this, I made sure to include module.exports=router in my JavaScript file. H ...

Utilize JavaScript to apply the CSS -moz-transition

Creating a web application and using CSS3 to transform a div, but encountering a challenge with Firefox. Able to make Chrome, Opera, and IE work properly, except for Firefox. Here's how I'm setting up the working browsers: obj.style.WebkitTrans ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

Solving the Cross-Origin Resource Sharing problem in AngularJS

While using the http dependency in AngularJS and setting headers for CORS, I am encountering an error. Please check the console.log for more information on the error. The error message reads: "XMLHttpRequest cannot load . Response to preflight request doe ...

Unable to alter Mui input label color upon focus using theme.ts

In my next.js app, I'm facing an issue with changing the color of the label in a Material UI input field using Mui. Despite updating the theme.ts file to change the border bottom color and label color, only the border bottom color is being applied. T ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...

What is the reason behind the automatic activation of a function when a nested React modal is

I've been experimenting with using react-responsive-modal and then switching to react-modal, but I'm encountering the same issue. Additionally, all my forms are built using react-hook-form. The problem arises when I have one modal triggering ano ...

Improving Javascript Arrays for Easier Reading

A dataset has been organized into a table format as shown below: +------+---------+----+----+----+----+-------+----------+ | Year | Subject | A | B | C | F | Total | PassRate | +------+---------+----+----+----+----+-------+----------+ | 2015 | Maths ...

React app experiencing freezing due to custom asynchronous function utilisation

I am currently facing an issue with my personal project where the application freezes under certain circumstances. The initial load works fine, but when I make changes to the code causing React to re-render, the app just freezes. It seems to be related to ...

Alert: Github Dependabot has flagged Babel as vulnerable to arbitrary code execution when compiling meticulously designed malicious code

My Github Repository's Security section is flagging this issue as Critical for both my Frontend and Backend code. I'm having trouble grasping the nature of this alert. Can someone explain what flaw it represents? After updating my dependencies, ...

What a great method to execute a button click within the same button click using jQuery!

Here's an example of code that attempts to make an ajax call when a user clicks a button. If the ajax call fails, the button should be reclicked. I've tried this code below, but it doesn't seem to work. $("#click_me").click(function(){ ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Here's a guide on using a button to toggle the display of password value in Angular, allowing users to easily hide

I have successfully implemented an Angular Directive to toggle the visibility of password fields in a form. However, I am facing an issue with updating the text displayed on the button based on the state of the input field. Is there a way for me to dynami ...

Uncovering the Mystery of Undefined Dom Ref Values in Vue 3 Templaterefs

I am currently experimenting with the beta version of Vue 3 and encountering an issue while trying to access a ref in the setup function. Here is my component: JS(Vue): const Child = createComponent({ setup () { let tabs = ref() console.log(t ...

Creating a vibrant and mesmerizing inward spiraling rainbow of colors on canvas using JavaScript

After coming across an image that caught my eye, I was inspired to recreate it using canvas: https://i.stack.imgur.com/fqk3m.png I've attempted drawing arcs starting from the center of the screen, but I'm struggling with getting their paths acc ...

Oops! The provided value for the argument "value" is not a valid query constraint. Firestore does not allow the use of "undefined" as a value

I encountered an error while exporting modules from file A and importing them into file B. When running file B, the error related to Firebase Cloud Firestore is displayed. const getMailEvents = (startTime, endTime) => { serverRef = db.collection("Ma ...

What is the best way to manage Page Refresh using Angular.js?

I recently followed the tutorial at http://scotch.io/bar-talk/setting-up-a-mean-stack-single-page-application This guide went over controllers and services using angular.js for a single-page application. However, when I try to directly access /pageName o ...

What is preventing the nativeEvent callback from being triggered in React Native's Animated.event() function?

Why isn't the nativeEvent callback triggering in my Animated.event call when dragging a box? I am working on implementing functionality to prevent draggable components from going off-screen using gesture control. However, I'm facing an issue whe ...

What is the best way to switch between components when clicking on them? (The component displayed should update to the most recently clicked one

I am facing a challenge in rendering different components based on the navbar text that is clicked. Each onclick event should trigger the display of a specific component, replacing the current one. I have 5 elements with onclick events and would like to re ...

The HTML elements may have identical heights, but visually, one appears larger than the other

The size of the "login to enter chat" button seems to be larger than the messageBox div, despite adjusting padding and margins. What could be causing this issue? Any suggestions on how to fix this design glitch? #chatbox { width: 500px; height: ...