Search code examples
cssreactjsdomdocument-body

React: cannot read document.body.style.marginRight


I am having trouble reading the margin-right css property of the body. It seems to fail on initial render, but a few times it seemed to work when I was manually setting the margin-right. I expect it has something to do when when the component is rendering. Tried in useEffect and useLayoutEffect without success.

Pertinent CSS:

body {
    margin-right: 10px;
}

Simple create-react-app:

function App() {
  const [marginRight, setmarginRight] = useState(
    document.body.style.marginRight
  );

  return (
    <div className="App">
      <p>BODY Right margin is: {marginRight}</p>
    </div>
  );
}

Edit k98p8r5ppv


Solution

  • HTMLelement.style only returns inline styles. To access style from your css file, you should use:

    window.getComputedStyle(document.body).marginRight