Passing state from a toggle button to hide a Div

Hi folks,

In a React project, I have a toggle button that shows and hides some info to the user. Now I want to connect a third part to the toggle.

For instance, a div is shown on when the page loads, then the toggle button is clicked then I want that to hide.

I need to know, how do I pass the state from one component to another to show visibility.

How do I pass the state to know to hide / show based on users clicking.

Cheers,

John.

You don’t pass the state from one to another, you write a component that contains the state that is a parent of both. The class is irrelevant here, you just don’t render the text when it shouldn’t be visible1. Example:

const Details = () => {
  const [isVisible, setIsVisible] = React.useState(false);

  return (
    <div>
      { isVisible && <p>So this needs to be hidden when the show details is click - how does one pass that state to this component so it knows to hide.</p> }
      <button onClick={() => setIsVisible(!isVisible)}>Show Details</button>
    </div>
</>)
};

1. using a class or style prop is useful if you want to animate, but in that case you always render the element but change the class/style based on it being visible or not. It's exactly the same process though.

1 Like

Thank you very much Dan!

1 Like