Search justacoding.blog. [Enter] to search. Click anywhere to close.

November 15th, 2021

Show And Hide Elements And Components In React

Showing and hiding elements and components in React is straightforward enough.

However, there are some caveats and some gotchas to consider in some scenarios.

Let’s dive right in!

Setting up a flag or indicator in state to track visibility

The mechanism to show and hide elements in React should work in conjunction with the component’s state.

Remember, changes to the component’s state will (typically) trigger a re-render. We can use this mechanism to conditionally show or hide the element(s) we want to target.

In React, this is what’s known as conditional rendering.

Adding an isVisible boolean

The first step to controlling element or component visibility in React is to initialize a flag to track whether the element should actually be visible or not.

Your component’s state should hold a boolean value, such as isVisible, which can be toggled (set to true or false) as per your own specific requirement and the business logic of the component:

const [isVisible, setIsVisible] = useState(true)

setIsVisible(false)
setIsVisible(true)

// Toggle whatever the current value is
setIsVisible(prevIsVisibleValue => !prevIsVisibleValue)

Toggling isVisible in this way means the component will re-render with the new value, which will effectively show or hide the target element (once we incorporate it into our JSX, below).

Let’s look at using isVisible within our JSX output, next.

Controlling element or component visibility in JSX

With the isVisible boolean added to the component’s state, it’s a matter of using this value in our JSX output.

So if isVisible is true, the element should remain visible. If it’s false, we want to hide the element instead.

There are several ways to go about doing this. Let’s look at these different approaches.

Using the logical && operator to show or hide elements

This is arguably the most common and most convenient approach.

We can simply use the logical and operator (&&) to control visibility:

{isVisible && <h5>Some element</h5>}

Think of this as a shortcut to an if statement.

We’re just checking for the truthyness of isVisible and showing the element if this evaluates to true.

There are some gotchas here, however.

Gotchas to consider when working with the && and the || operators

It’s perhaps not super common, but it is possible to experience some unexpected output when using these operators if you aren’t familiar with how JavaScript’s type coercion mechanism works.

This caveat is not limited to or specific to React.

Consider this example:

const isVisible = true
let age = 22

{isVisible && age && <h5>Your age is: {age}</h5>}
// outputs a h5 with text "Your age is 22"

(In the example above, let’s say we don’t know it the age variable is set, and we want to check for it before outputting the relevant element in our JSX)

In this case, you’ll see the h5 rendered out, as expected.

However, in this case:

const isVisible = true
let age = 0

{isVisible && age && <h5>Your age is {age}</h5>}
// simply outputs a 0

You won’t.

Instead, you’ll see a 0 rendered instead.

But why is that?

It’s down to JavaScript type coercion and how it evaluates statements such as this one.

In short, JavaScript is considering our age variable to be falsy this time — so it’s outputting this instead of the target element, the h5. It’s doing this because isVisible is true.

If that’s confusing, I have an article on the or operator that speaks more in depth about type coercion (it can also be applied to the and operator in very much the same way). So I’d advise checking that out, it’s well worth brushing up on!

It’s worth nothing that this is something of an edge case, but it can be very easy to get caught out by this type of issue.

Using the ternary operator to control element visibility

Similarly, you can use the ternary operator to show and hide elements in React, too.

This is just like the logical && operator example above, but you can also supply an else expression to the statement:

{showAge ? <h5>Your age is {age}</h5> : <h3>Age hidden</h3>}

So if the condition evaluates to true, React will render the first expression.

If false, it’ll render the second one.

This is obviously useful when you want to show an element when some other element is hidden, or vice-versa. It’s like a shortened if/else, really.

Adding a CSS class to show or hide an element

You can also control the visibility of an element with a simple CSS class, like so:

.element {
  display: none;
}

.visible {
  display: block;
}

Assuming our element is hidden by default, we can toggle the visible class as required:

<div className={`${isVisible ? : "visible" : ""}`}>Some element</div>

Typically, you’ll want to use the logical && operator when showing or hiding elements. However, there are use-cases for this approach.

Let’s say your component handles some form input fields, and some of those fields should be hidden from the user. But you still want the fields to pass their values to your backend service in subsequent network requests.

If you aren’t passing the form data by some other mechanism, and you’re relying on the form data directly — this would be one possible approach to ensure that the form data of the hidden fields is still passed.

If the field wasn’t rendered at all (as would be the case when using the logical && operator) the form data for this specific field wouldn’t be passed at all (as it simply wouldn’t exist in the DOM to begin with).

Using the standard if statement

Lastly, you can use a standard if statement to show or hide your element as required.

You can’t do this directly in JSX. But if your element is rendered via a function (which is in turn used in JSX) you can of course apply the standard if statement like so:

const outputHeader = () => {
  if (isVisible) {
    return <h1>The header</h1>
  }
}

// somewhere in the render method...
{outputHeader()}

This approach (using a function outside of JSX) is fairly useful if you have a lot of conditionals in place.

It’s often cleaner and easier to read if you have a function that specifically handles these cases, rather than nesting many different conditions in one ternary statement or something similar.

Showing and hiding components in React

If you’re wanting to show or hide components in React, as opposed to other elements (like divs or headers) it works exactly the same way as in the examples provided above.

You can simply reference the isVisible boolean value from state and either show or hide the component as required:

{isVisible && <MyComponent />}

There is one caveat, however (or at least, something to be aware of) when conditionally rendering components as opposed to elements.

Conditional rendering will mount the component again

One thing to be aware of is that conditional rendering will re-mount the component in question.

If you have some behaviour happening on mount (or more specifically, after the first render) in your component, for example:

useEffect(() => {
  console.log("Component mounted!")
}, [])

This behaviour will be triggered when the component becomes visible once again.

That’s the key difference when conditionally rendering components as opposed to elements.

With components, there may be side-effects that take place.

We aren’t simply showing or hiding the component. We’re actually remounting it. So the side-effects of doing this must be taken into account!

Avoiding these side-effects when showing and hiding the component

One way around this is to show or hide the component via a CSS class, as described above. This would be passed in as a prop and would be applied directly to the container div within.

This approach should perhaps be used sparingly, however.

Alternatively, and perhaps more effectively, you can handle the visibility using the logical && operator — but from within the target component, instead of outside of it.

So instead of doing:

{isVisible && <MyComponent />}

You can do:

<MyComponent isVisible={isVisible} />

const MyComponent = ({ isVisible }) => {
  if (isVisible) {
    return <h5>My component</h5>
  }
  return null
}

And then utilize this isVisible prop within the target component.

If isVisible is true, display the component as normal.

If it’s false — return null from the component instead.

By doing this, the component is always actually rendered by React, and thus showing and hiding it won’t trigger the various lifecycle methods (or useEffect functionalities) you’d expect.

The difference is that the visibility of what the component returns is controlled instead, not the actual component itself.

In summary

I hope you’ve enjoyed this article!

We’ve stepped through a few different approaches with regards to showing and hiding elements and components in React.

As stated, there are a few caveats to consider in some scenarios.

If you’re interested in other articles like this one, please do feel free to check out my React and JavaScript categories, and remember to check back later for similar content!

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog