How to apply CSS to body element if prop is present?

Viewed 311

If the open prop value is true I want to apply a position fix to the body element, how can I achieve that using styled components?

export const Navbar = styled.nav`
  box-sizing: border-box;
  overflow-y: scroll;
  justify-content: center;
  background: ${() => "#ffffff"};
  height: 100vh;
  text-align: left;
  padding: 5rem 4rem 2rem;
  top: 0;
  left: 0;
  transition: transform 0.3s ease-in-out;

  transform: ${({ open }) => (open ? "translateX(0)" : "translateX(-110%)")};
 

  body {
    position: ${({ open }) => (open ? "fixed" : "absolute")};
  }
2 Answers

I'm not familiar with react styled components but I doubt that the syntax with the nested body tag is correct.
You could use a useEffect hook inside your Navbar component though:

useEffect(() => {
  document.body.style.position = open ? 'fixed' : 'absolute';
}, [open]);

This will call the arrow function initially and whenever the open prop changes.

The right way is to use the library API as querying the document-object/DOM is an anti-pattern in React (that's why you using React in first place).

See body style example:

const GlobalStyle = createGlobalStyle`
body {
  color: ${({ open }) => (open ? "red" : "blue")}
}
`;

export default function App() {
  const [open, toggle] = useReducer((p) => !p, false);
  return (
    <>
      Body Style Example
      <GlobalStyle open={open} />
      <button onClick={toggle}>toggle</button>
    </>
  );
}

Edit Body Style Example

Related