Categories
React Answers

How to access styles of an element from React?

Spread the love

Sometimes, we want to access styles of an element from React.

In this article, we’ll look at how to access styles of an element from React.

How to access styles of an element from React?

To access styles of an element from React, we can assign a ref to the element that we want to get the styles for.

And then we can use the window.getComputedStyle method to get the style from the element’s ref.

For instance, we write:

import React, { useEffect, useRef } from "react";

export default function App() {
  const ref = useRef();
  useEffect(() => {
    const computed = window
      .getComputedStyle(ref.current)
      .getPropertyValue("border-radius");
    console.log(computed);
  }, []);

  return (
    <div ref={ref} style={{ borderRadius: "5px" }}>
      hello world
    </div>
  );
}

We create a ref with the useRef hook.

Then we assign the ref to the div.

Next, we get the border-radius style of the div when the div is rendered by using:

const computed = window
   .getComputedStyle(ref.current)
   .getPropertyValue("border-radius");

We put the code in the useEffect callback so it’ll run when the component is mounted.

As a result, we get that computed is 5px since we set the borderRadius of the div to 5px.

Conclusion

To access styles of an element from React, we can assign a ref to the element that we want to get the styles for.

And then we can use the window.getComputedStyle method to get the style from the element’s ref.

Leave a Reply

Your email address will not be published. Required fields are marked *