sin tribu
sin tribu

Reputation: 1180

Assign style to react component like javascript element.style.width = width syntax

I'm wondering if there is a way to add styles and attributes to a react component using syntax like the following.

const rect = <rect></rect>
rect.style.fill = "black" 
rect.style.height = "50px"
rect.style.width = "50px"

This doesn't work (or I wouldn't be asking) but is there something similar?

Thanks!

Upvotes: 1

Views: 484

Answers (1)

kind user
kind user

Reputation: 41893

It is possible, using refs.

const { useEffect, useRef } = React;

const App = () => {
  const ref = useRef(null);
  const rect = <div ref={ref}></div>;
  
  useEffect(() => {
    ref.current.style.background = "black";
    ref.current.style.height = "50px";
    ref.current.style.width = "50px";
  }, []);
  
  return rect;
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Upvotes: 2

Related Questions