Home > Back-end >  Getting active background color using useRef
Getting active background color using useRef

Time:05-18

Given the css

.App {
  font-family: sans-serif;
  text-align: center;
}
.App:hover {
  background-color: red;
}

and jsx code

import "./styles.css";
import { useRef } from "react";

export default function App() {
  const r = useRef();
  const handleClick = () => {
    console.log(r.current.style.backgroundColor);
  };
  return (
    <div className="App" ref={r} onClick={handleClick}>
      something
    </div>
  );
}

See codesandbox I want to get the active background color of div (which is red). But the code give me nothing. What's the right way of doing that?

CodePudding user response:

.style only tells you the inline style on the element, and this div has no inline style. If you want to know the style that results when combining inline style and css selectors, you need getComputedStyle

const handleClick = () => {
  console.log(window.getComputedStyle(r.current).backgroundColor);
}

CodePudding user response:

el.style.X is not working correctly. Insteadof this use window.getComputedStyle(el) and u can get full list of styles. As a example u can see it.

  • Related