How to show and hide components in React using React Hook

Last updated on Nov 8, 2020 by Suraj Sharma



In this tutorial, you will learn to conditionally show and hide components in React using the useState() hook.


JSX supports JavaScript if-else statements and the JavaScript ternary operator to conditionally render React components.


In below examples, we are going to see how we can use both if-else and ternary operator.


Consider, we have a simple function component <ToggleElement />, which shows and hides a <Typography /> component on click of a Toggle Button


const ToggleElement = () => {
  const [isShow, setIsShow] = React.useState(true);

  const handleClick = () => {
    setIsShow(!isShow);
  };

    return (
    <>
      <Typography>
        show/hide typography
      </Typography>
      <button onClick={handleClick}>Toggle</button>
    </>
  );
};


Let’s define the Typography Component


  const Typography = (props) => {
    return <p>{props.children}</p>;
  }


Now inside the ToggleElement component, we are going to use three different ways to show and hide the Typography element on click of the button


1. Using if-else statement



if (isShow) {
    return (
    <>
      <Typography>
        show/hide typography
      </Typography>
      <button onClick={handleClick}>Toggle</button>
    </>
  );
} else {
  return <button onClick={handleClick}>Toggle</button>
}




return (
  <>
    {isShow ?
      <Typography>
        show/hide typography
      </Typography>
    :
      <></>
    }
    <button onClick={handleClick}>Toggle</button>
  </>
}


3. Using && Operator



return (
  <>
    {isShow &&
      <Typography>
        show/hide typography
      </Typography>
    }
    <button onClick={handleClick}>Toggle</button>
  </>
);


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.