Home > Blockchain >  Add Underline When Hover in React and CSS
Add Underline When Hover in React and CSS

Time:04-20

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>

CodePudding user response:

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

CodePudding user response:

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).

CodePudding user response:

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";
}
  • Related