React setState with multiple components

I want to click a button and set the value of a variable to something specific. The issue is that I have two buttons in two different components that I want to be able to modify this variable. Is this a scope issue? Am I using components wrong? Here is my example code, sorry for such a weird example, my real project is way too long.

import "./styles.css";

export default function App() {
  return (
    <div className="App">
      
      <Header/>
      <Article/>
    </div>
  );
}

function Header() {
  // const [open, setOpen] = useState(false);
  //use with setOpen(true)
  return (
    <header>
      <nav>
        <button onClick={null}>
          red
        </button>
      </nav>
      <div id="title">
        <h1>Title Here!</h1>
      </div>
    </header>
  );
}

function Article(){
  return(
    <article>
      <p>qwertyuiop</p>
      <button onClick={null}>
          blue
        </button>
    </article>
  )
}

It sounds like you need to lift up state. If you have components that all need access to the same state, then you need to move that state to a common ancestor. You can pass that value down to its descendants and also pass down callback functions to any that need to change that state. I once made a pen to help show how this works.

That is the “standard” way to do it. You can also use things like context and tools like Redux, but it’s better to master the basics first.

I will look into that. Thanks!

I finally figured it out. Here is an article about lifting up state using hooks and functional components.

Cool, I’m glad you’ve figured it out. Of course, it can be done with class components too, but FCs and hooks are definitely one way to go, and will probably be increasingly common as time goes on.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.