Delving Developer

Master Showing and Hiding Elements in React

Eddie Cunningham
Eddie Cunningham
4 min readReact.js
Cover Image for Master Showing and Hiding Elements in React

Welcome to the ultimate guide on how to show and hide elements in React applications! Creating dynamic user interfaces is a key feature of modern web applications, and understanding how to conditionally render elements is an important tool in your developer toolbox.

In this article, we will delve into different approaches to show and hide elements in React. We will cover the following topics:

  1. Conditional rendering with ternary operator
  2. Using boolean values for conditional rendering
  3. CSS-based solutions
  4. Common "gotchas" and how to avoid them

By the end of this article, you will be equipped with the knowledge required to build powerful and responsive user interfaces using various techniques of showing and hiding elements.

Conditional rendering with ternary operatorlink

The ternary operator is one of the most popular and simple ways to show and hide elements in React. It's an inline solution which has a great advantage of not making your code less readable. Here's an example of how to use it:

import React, { useState } from "react";

function App() {
  const [showContent, setShowContent] = useState(true);

  const toggleContent = () => {
    setShowContent(!showContent);
  };

  return (
    <div>
      <button onClick={toggleContent}>Toggle Content</button>
      {showContent ? <p>Content is visible</p> : null}
    </div>
  );
}

In this code snippet, we use the useState hook to manage the showContent state. The button onClick handler toggles the state of showContent. Within the render method, the ternary operator handles the showing and hiding of the content.

Returning null means that the component doesn't render anything.

Using boolean values for conditional renderinglink

You can use boolean values to conditionally render elements in React. Returning false means that the component doesn't render anything. Here's an example:

import React, { useState } from "react";

function App() {
  const [showContent, setShowContent] = useState(true);

  const toggleContent = () => {
    setShowContent(!showContent);
  };

  return (
    <div>
      <button onClick={toggleContent}>Toggle Content</button>
      {showContent && <p>Content is visible</p>}
    </div>
  );
}

In this example, we use the && operator to conditionally render the component. If showContent is true, the content will be displayed, otherwise it will be hidden.

CSS-based solutionslink

Relying on CSS to toggle visibility of elements in React is another useful technique. This approach has the advantage of offloading some logic to CSS, potentially improving performance, and keeping the DOM consistent.

One way to do this is by using the CSS display property:

import React, { useState } from "react";

function App() {
  const [showContent, setShowContent] = useState(true);

  const toggleContent = () => {
    setShowContent(!showContent);
  };

  return (
    <div>
      <button onClick={toggleContent}>Toggle Content</button>
      <p style={{ display: showContent ? 'block' : 'none' }}>Content is visible</p>
    </div>
  );
}

Here, we set the display property of the content element to block or none, depending on the state.

Another alternative is using CSS classes:

/* App.css */
.showContent {
  display: block;
}

.hideContent {
  display: none;
}
import React, { useState } from "react";
import "./App.css";

function App() {
  const [showContent, setShowContent] = useState(true);

  const toggleContent = () => {
    setShowContent(!showContent);
  };

  return (
    <div>
      <button onClick={toggleContent}>Toggle Content</button>
      <p className={showContent ? 'showContent' : 'hideContent'}>Content is visible</p>
    </div>
  );
}

In this example, we import a CSS file and switch CSS classes based on the state.

Common "Gotchas" and How to Avoid Themlink

While React makes it simple to conditionally render components, there are certain pitfalls to be aware of - even for experienced developers. In this section, we will explore these "gotchas" and provide some guidance on how to avoid them, ensuring smooth sailing when showing and hiding elements in your applications.

Numbers in the left-hand side of && operator

When using the && operator for conditional rendering, you may encounter unexpected results when using numbers, especially 0. Given the nature of JavaScript type coercion, equating 0 to false can create confusion. Consider the following example:

function App() {
  const numberOfItems = 0;

  return (
    <div>
      {numberOfItems && <p>You have {numberOfItems} items in your cart.</p>}
    </div>
  );
}

In this code snippet, instead of hiding the content, you will surprisingly see 0 rendered on the screen. This is because 0 is considered as false in a conditional statement, but not omitted when rendering using the && operator.

To avoid this issue, ensure you're comparing a boolean value, like so:

function App() {
  const numberOfItems = 0;

  return (
    <div>
      {(numberOfItems > 0) && <p>You have {numberOfItems} items in your cart.</p>}
    </div>
  );
}

In this revised version, numberOfItems > 0 is a boolean expression that avoids rendering 0 when we do not want it to be displayed.

Be cautious with undefined

React components can inadvertently return undefined, which will not render anything to the screen. However, this isn't the idiomatic approach in React, and returning null is always preferable. You may encounter issues with third-party libraries or linters if you don't properly handle undefined.

Always ensure you return null instead of undefined when you don't want to render anything:

function App() {
  const numberOfItems = 0;

  if (!numberOfItems) {
      return null;
  }

  return (
    <div>
      <p>You have {numberOfItems} items in your cart.</p>
    </div>
  );
}

These techniques of showing and hiding elements are the most common and effective for managing your React applications. By mastering these concepts, you will be well-equipped to create dynamic and responsive user interfaces. Happy coding!