How to Add Underline Effect on Hover using React and CSS

Is there a way to add an underline in text-decoration when hovering over the text? I've tried the code below but it doesn't seem to be working.

CLICK HERE

       <span
        style={{
          color: "red",
          cursor: "pointer",
          "& :hover": {
            textDecoration: "underline"
          }
        }}
      >
        Click this.
      </span>

Answer №1

The style property does not have support for selectors.

To properly implement your styling logic, it is recommended to transfer it into a <style> element or a linked stylesheet <link>.

There are numerous React-friendly libraries available that can assist in generating styles dynamically. An example of this is Styled Components, which is well-known for supporting the SCSS syntax you are utilizing (with the exception of an extra space after the &).

import { styled } from 'styled-components';

const MySpan = styled.span`
    color: red;
    cursor: pointer;
    &:hover {
        text-decoration: underline;
    }
`;

Following that,

<MySpan>Click this.</MySpan>

However, it should be noted that span elements are not intended for interaction. They are not identified as clickable by screen readers and cannot be tabbed to without using a mouse. This presents a significant accessibility obstacle. If there is a need for users to interact by clicking on something, it is advisable to use a link (if directing somewhere) or a button (for other interactions).

Answer №2

As discussed in this article:

There has been a strong argument against using react inline styles, citing the lack of support for CSS selectors like ":hover", ":active", ":focus", ":before", ":after", media queries, and SCSS syntax.

The recommendation here is to stick with using a CSS file and applying styles through classes instead, for example with class:hover.

Answer №3

give this a shot, I gave it a try and it actually does the trick.

Here is the code in App.js:

import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <span
        style={{
          color: "red",
          cursor: "pointer"
        }}
      >
        Click here.
      </span>
    </div>
  );
}

And in style.css:

.App {
  font-family: sans-serif;
  text-align: center;
}

span:hover {
  text-decoration: underline !important;
  color: "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

Package Compiler & React Server Rendering

I recently integrated Parcel Bundler to bundle my client files for React Server Side Rendering. After setting up the Parcel Middleware and specifying the location of my client entry point, I noticed that although Parcel was bundling my files, the ReactDOM ...

The custom server was functioning properly, but as soon as I altered the file directory, an error occurred on Next.js

After creating "create-next-app," I successfully set up the folder structure as follows: +client2 --.next --node_modules --public --... --server.js However, when I move my "server.js" file to a different location: +client2 --.next --no ...

I'm curious if it's possible to superimpose a png image and specific coordinates onto a map by utilizing react-map

I am attempting to showcase a png graphic on a react-map-gl map, following the approach outlined here. Unfortunately, the image is not appearing as expected and no error messages are being generated for me to troubleshoot. Below is the snippet of code I&a ...

Is there a reflow triggered by `window.matchMedia` function execution?

When creating a webpage, it's important to minimize "layout thrashing" or "reflow", which occurs when the browser recalculates the dimensions and positions of all elements on the page. Paul Irish has compiled a valuable list of processes that trigger ...

In Reactjs, Axios and fetch are both commonly used for sending ongoing network requests to localhost

In order to establish a successful connection between the express backend and MongoDB database, I initially used fetch("/") from the frontend, which returned the index.html code. However, when I switched to fetch("http://localhost:9000"), I encountered a C ...

Struggling to properly position content with Bootstrap and CSS

I have been tasked by my mentor to create a website based on a wireframe that he sent me. However, I am facing difficulty in positioning the text on these "hero" images. https://i.sstatic.net/Xw19o.jpg https://i.sstatic.net/uBdaa.jpg The text seems to be ...

The mobile menu dropdown link in jQuery is not functioning as expected

I am having an issue with my drop down menu links - they are not clickable. Every time I try to click on them, the menu just closes back to its original position and nothing happens. If you want to see the issue, you can check out my fiddle here. EDIT: T ...

Monitoring changes to a property of an object within an observable array using MobX

Currently, I am working with reactjs and mobx. My situation involves an observable array composed of Item objects that I aim to display while showcasing live property changes by observing the properties on the objects within the array. These changes do not ...

Utilizing jQuery for easy drag-and-drop functionality in web development

I have two lists which are currently using jQuery for functionality. An example can be found here. I need the same basic functionality but with some modifications: Instead of just getting all sortable items by clicking "Get items," I want to be able to dr ...

How can we determine the dimensions of an absolutely positioned element within a relatively positioned element?

One thing I noticed is that when placing an absolutely positioned element within a relatively positioned element, the latter does not automatically inherit the width and height of the former unless manually set. Take this example: <!DOCTYPE html> ...

What is the most efficient way to retrieve the two smallest numbers using jQuery?

I am trying to find the two smallest numbers out of a set of three, and then I want to display them on the screen. In PHP, we usually use echo to display values on the screen. However, with this code snippet, I am only able to get one smallest value instea ...

What is the method for altering the background color of an input field upon entering text?

As a beginner in Javascript and jQuery, I am struggling to understand why my code is behaving the way it does. I have written two similar functions aimed at changing the background color of an input field. The objective is to set the background color of t ...

When I tried to open a website using the "target=_blank" attribute on the Chrome mobile version for iPhone, I noticed some strange viewport behavior

[Update] I encountered the following issue: I once had a website. It functioned well, except when opened in a new tab with target "_blank." When accessing the site directly, everything appeared normal enter image description here However, when accessed ...

When working with React Native, encountering an issue where passing props using the Map function results in an error stating "undefined is not a function" near the section of code involving the

Hey there! I'm currently facing an issue with fetching data from my Sanity CMS and passing it as props to a child component. Interestingly, the same code worked perfectly on another screen, but here I seem to be encountering an error. Although the dat ...

Issue with locating Entry module in React - Update needed for Visual Studio RC 2017

Greetings! I am encountering an issue while trying to run my webpack (task runner). Click here for the development image I want to mention that I have also installed npm. Below is the configuration of my webpack: "use strict"; const path = require(&ap ...

Is there a way to customize the color of the navbar dropdown that appears when the screen size is shrunk?

The current code I have is producing this result. Visit the website I am looking to modify the color of: the three bars Is there a way to do this? I used the nav element for this. Even though I already have custom CSS for navbar colors, I am unsure ho ...

Is VSCode spontaneously classifying the entire project as untracked without any apparent reason?

This issue could be related to extensions or the VS Code settings configuration, as I have never encountered it before. All files are being randomly listed as untracked. Current Version: 1.86.2 (Universal) To visualize the problem, here is an image: ht ...

Is there a way to efficiently retrieve data in React when deploying the project?

Currently, everything runs smoothly when using the npm run dev script. However, I am facing an issue where images in testimonials.avatar do not display when using the npm run build command. const Testimonials = ({ testimonials }) => { return ( < ...

IE11 causing overflow issues with flex item set to 0% basis

This straightforward example can be viewed in the following codepen link: http://codepen.io/anon/pen/Mazjyv. It showcases a button that acts as a flex item with a flex-basis set to 0%. While other browsers handle the content within the button container wi ...

Is it possible that the styleOverrides in MUI themes aren't actually overriding anything?

I have recently made the switch from MUI version 4 to version 5, but my app's appearance has taken a turn for the worse! One major issue I am facing is that many of the theme properties seem to be overridden by the default values. Take this example th ...