'show / hide component based on if else statement in react

I have some code that looks like this

const Movies = () => {
  const [show, setShow] = useState(false);
  const [show1, setShow1] = useState(false);
  const onClick = () => setShow(!show);
  const onClick1 = () => setShow1(!show1);

  return (
    <div className="movie">
      <Header />
      <h2>Discover a new movie!</h2>
      <div className="showBtns">
        <button onClick={onClick} className="right">Search <FaSearch /></button> 
        <button onClick={onClick1}>Discover <FaSearch /></button>
      </div>
      {show1 ? <DropDown /> : null } 
      {show ? <MovieSearch /> : null } 
      <Nav />
    </div>
  );
};

as of right now if I click on the button for either one it will show the corresponding component but if both are clicked they both show up.

I'd like to write an if else statement to check if one is showing then the other should not be shown.

I've tried a few different things and can't seem to get it to work.

any feedback on a better way to do this or how to get it to work would be appreciated.

if(show === true){
    setShow1(false)
  } else if(show1 === true) {
    setShow(false)
  }

this gives an error of Too many re-renders. React limits the number of renders to prevent an infinite loop.



Solution 1:[1]

You can handle the hiding/showing logic for these button in the click events because that is where the state changes.

Example: https://codesandbox.io/s/wild-water-f5nzor?file=/src/App.js

Solution 2:[2]

You can modify your onClick functions like this: const onClick = () => setShow((prevState) => !show1 && !prevState); const onClick1 = () => setShow1((prevState) => !show && !prevState);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 berkininan
Solution 2 can özfuttu