1

How do I add a underline in text-decoration when hovering the text? Seems this is correct but it still doesn't work

CLICK HERE

       <span
        style={{
          color: "red",
          cursor: "pointer",
          "& :hover": {
            textDecoration: "underline"
          }
        }}
      >
        Click this.
      </span>
6
  • & :hover would apply to a hovered descendant of the current element. You want &:hover Commented Apr 20, 2022 at 9:54
  • You are using less syntax, sure that's implemented in your project? Commented Apr 20, 2022 at 9:55
  • @CBroe. Tried &:hover but same thing. underline doesnt appear Commented Apr 20, 2022 at 9:57
  • Then you probably don't have less pre compiler. Use a regular className with some css. Commented Apr 20, 2022 at 9:58
  • Does this answer your question? How can I access a hover state in reactjs? Commented Apr 20, 2022 at 9:58

3 Answers 3

4

The style property doesn't support selectors.

You need to move your logic into a <style> element or a <link>ed stylesheet.

There are plenty of React-friendly libraries for generating them on-the-fly for you. Styled Components is a popular tool for this which supports the SCSS syntax you are (almost — you have a rogue space after the &) using.

import { styled } from 'styled-components';

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

and then

<MySpan>Click this.</MySpan>

However, span elements are not designed to be interactive. They are not announced as clickable by screen readers and you can't tab to them if you aren't using a mouse. This is a major accessibility barrier. If you want something for the user to click on, use a link (if you are linking somewhere) or a button (otherwise).

Sign up to request clarification or add additional context in comments.

Comments

1

According to here:

There has been plenty of valid points made that react inline style is not a good idea. No support for CSS selectors like “:hover”, “:active” “:focus”, “:before” and “:after”, media queries, nor for SCSS syntax, to name a few.

Just use a css file and implement it there with class:hover

Comments

1

try this, I Tried it and it works.

App.js:

import "./styles.css";

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

style.css:

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

span:hover {
  text-decoration: underline !important;
  color: "red";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.