paytoncodes
paytoncodes

Reputation: 92

React: How to use child component's state to affect parent container's styles?

So I'm working on translating my portfolio into React. My original website has a toggler button that has a pretty simple onclick function that toggles the class of the container, it's all a single html file and single script file, I think I have a hard time with React because there's so many layers.

Here is the code sandbox for what I have so far for the React app.

The Toggler component is inside of a Navbar, which is inside of a BaseLayout, which has a container with the class 'light'. My goal is for the toggler in the navbar to change that container's class back and forth between 'light' and 'dark'.

This is what the Toggler looks like.

export default function Toggler() {
  let [theme, setTheme] = useState("light");

  function handleClick() {
    theme === "light" ? setTheme("dark") : setTheme("light");
  }

  return (
    <div className={Style.toggler} onClick={handleClick}>
      {theme === "light" ? <span>🌑</span> : <span>🌕</span>}
    </div>
  );
}

What I'm having trouble with is exporting that state logic back to the BaseLayout so that the container's class can change. Any help is greatly appreciated! I'm still fairly new to React to sorry if this is a silly question.

Upvotes: 0

Views: 190

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074839

Things like themes are where context is useful. You wrap your entire component tree in the context, and in the theme button, you use a setter in the context that updates the context's state.

That link has this full example which does exactly that (in fact, to toggle themes, as it happens :-) ).

Upvotes: 3

Related Questions