Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting active background color using useRef

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

.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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading