Hiding a component means that the component is rendered, but invisible. Alternatively, you can use conditional rendering to not render an element at all.

Hide element in React

Let’s see how to hide an element or a component in React.

<h1 style={{display: "none"}}>Hello, World</h1>

Header element will stay hidden until you manually change the inline style. Usually you want something more dynamic. For example, show or hide an element in response to user events.

Hide a component on button click in React

You need state to dynamically hide element in React.

Let’s say you have a state variable hidden. It represents current state – whether element should be shown or hidden.

function App() {
  const [hidden, setHidden] = useState(true);
  return (
      <h1 style={{ display: hidden ? "none" : "block" }}>Hello, World</h1>
      <button onClick={() => setHidden(!hidden)}>
        {hidden ? "show" : "hide"}

If the element is hidden, clicking the button will show it. If the element is displayed, then clicking will hide it.

As a cherry on top, text of the button also changes accordingly.

We use ternary operator and output different text of a button depending on the same state variable that we use for conditional styling.

Hiding vs not rendering

You can avoid displaying an element or a component by not rendering it.

Or the element will be rendered in the DOM, but it will be hidden.

The biggest difference between hiding and not rendering is element’s presence in the DOM. Hidden elements are rendered, but invisible.

If you don’t render an element, it will not be inserted into the DOM.