No Time Dad

A blog about web development written by a busy dad

React Hide Component Example

It’s often helpful to be able to show and hide React components. There are more than a few ways to accomplish this, some without even using JavaScript at all, instead relying on css. I’ll be showing a React hide component example here that does use JavaScript and is the preferred way of hiding elements, especially togglable elements, using React.

The css version would use a selector with display: none;, which removes the element from the accessibility tree, preventing it from being read by screen readers. This is what I want to happen if I’m hiding an element. I don’t want it to be just visually hidden.

Below is a react hide component example. Try clicking the button to the show and hide behavior.

// package.json
...
"react": "^17.0.2",
...
import React, { useState } from "react"

export const ToggleWrapper = ({ children }) => {
  const [hidden, setHidden] = useState(true)
  return (
    <div>
      <button onClick={() => setHidden(!hidden)} type="button">
        {hidden ? "Click to show" : "Click to hide"}
      </button>
      <div>{!hidden && children}</div>
    </div>
  )
}

export const MyComponent = () => <div>Hello!</div>
<ToggleWrapper>
  <MyComponent />
</ToggleWrapper>

The idea here is that the ToggleWrapper component contains a state variable called hidden that determines whether the children prop should be shown or hidden. A button in the component sets the hidden value. The {!hidden && children} inside the div element is essentially an if statement that when true, will display the children prop.

I like this pattern because it’s flexible and reusable. I can pass any component I want as a child to the ToggleWrapper component and I’ll be able to show and hide it via the button click. I try to use React’s children prop as much as possible in my development workflow. It’s a convenient way to build reusable components.