Home > front end >  show / hide component based on if else statement in react
show / hide component based on if else statement in react

Time:04-12

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related