Show and Hide ReactJS Components

Working with ReactJS for over eight years, I’ve encountered many situations where controlling the visibility of components is crucial. Whether you’re building a dashboard with dynamic content or a form that reveals extra fields based on user input, knowing how to show and hide components efficiently is an essential skill.

In this article, I’ll walk you through simple and effective methods to toggle the visibility of React components. I’ll share firsthand tips and full working code examples, so you can apply these techniques directly in your projects.

Show and Hide Components in React

React’s component-based architecture makes UI management easy, but sometimes you need to display or hide parts of the UI based on user actions or application state. For example:

  • Showing a login form when a user clicks “Sign In”
  • Hiding a sidebar on smaller screens
  • Displaying error messages conditionally

Mastering this will help you create interactive and user-friendly applications.

Method 1: Conditional Rendering Using State

The most common way I toggle component visibility is by using React’s state and conditional rendering.

Here’s a simple example:

import React, { useState } from "react";

function ShowHideExample() {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = () => setIsVisible(!isVisible);

  return (
    <div style={{ padding: "20px" }}>
      <button onClick={toggleVisibility}>
        {isVisible ? "Hide Details" : "Show Details"}
      </button>

      {isVisible && (
        <div style={{ marginTop: "10px", border: "1px solid #ccc", padding: "10px" }}>
          <h3>Details Section</h3>
          <p>This section is visible because the state is set to true.</p>
        </div>
      )}
    </div>
  );
}

export default ShowHideExample;

You can refer to the screenshot below to see the output.

Show and Hide Components ReactJS
  • We use the useState hook to keep track of visibility.
  • Clicking the button toggles the isVisible state.
  • The component inside {isVisible && (…)} only renders if isVisible is true.

This approach is simple, readable, and works well for most use cases.

Method 2: Use CSS to Show/Hide Components

Sometimes, you might want to keep the component mounted but just hide it visually. This is useful if the component has internal state or animations that you don’t want to reset.

Here’s how I do it with CSS:

import React, { useState } from "react";

function CssToggleExample() {
  const [isVisible, setIsVisible] = useState(false);

  const toggleVisibility = () => setIsVisible(!isVisible);

  return (
    <div style={{ padding: "20px" }}>
      <button onClick={toggleVisibility}>
        {isVisible ? "Hide Info" : "Show Info"}
      </button>

      <div
        style={{
          marginTop: "10px",
          padding: "10px",
          border: "1px solid #ccc",
          display: isVisible ? "block" : "none",
        }}
      >
        <h3>Info Section</h3>
        <p>This section is toggled using CSS display property.</p>
      </div>
    </div>
  );
}

export default CssToggleExample;

You can refer to the screenshot below to see the output.

Show and Hide Components in ReactJS
  • The component remains mounted, preserving its internal state.
  • Useful for animations or when you want to avoid costly unmount/mount cycles.
  • Simple to implement with inline styles or CSS classes.

Method 3: Conditional Rendering with Ternary Operator

Another way I toggle components is by using the ternary operator. This is handy when you want to show one component or another based on a condition.

Example:

import React, { useState } from "react";

function TernaryToggle() {
  const [loggedIn, setLoggedIn] = useState(false);

  return (
    <div style={{ padding: "20px" }}>
      <button onClick={() => setLoggedIn(!loggedIn)}>
        {loggedIn ? "Logout" : "Login"}
      </button>

      {loggedIn ? (
        <div style={{ marginTop: "10px" }}>
          <h2>Welcome back, User!</h2>
          <p>You are logged in.</p>
        </div>
      ) : (
        <div style={{ marginTop: "10px" }}>
          <h2>Please log in to continue.</h2>
        </div>
      )}
    </div>
  );
}

export default TernaryToggle;

You can refer to the screenshot below to see the output.

Show and Hide ReactJS Components
  • When you want mutually exclusive views.
  • For example, login vs logout states, or showing a form vs a confirmation message.

Method 4: Use React Fragments and Short-Circuit Evaluation

Sometimes you want to conditionally render multiple components or elements without extra div wrappers.

You can combine React Fragments with short-circuit evaluation:

import React, { useState } from "react";

function FragmentToggle() {
  const [showExtras, setShowExtras] = useState(false);

  return (
    <>
      <button onClick={() => setShowExtras(!showExtras)}>
        {showExtras ? "Hide Extras" : "Show Extras"}
      </button>

      {showExtras && (
        <>
          <p>Extra detail 1</p>
          <p>Extra detail 2</p>
        </>
      )}
    </>
  );
}

export default FragmentToggle;

This keeps your DOM clean and avoids unnecessary wrappers.

Real-World Example: USA Election Dashboard

Imagine you’re building a dashboard for the USA election results. You want to show detailed county-level data only when a user clicks on a state.

Here’s a snippet illustrating this:

import React, { useState } from "react";

const statesData = [
  { name: "California", counties: ["Los Angeles", "San Diego", "San Francisco"] },
  { name: "Texas", counties: ["Harris", "Dallas", "Tarrant"] },
];

function ElectionDashboard() {
  const [selectedState, setSelectedState] = useState(null);

  return (
    <div style={{ padding: "20px" }}>
      <h1>USA Election Dashboard</h1>
      <ul>
        {statesData.map((state) => (
          <li key={state.name} style={{ marginBottom: "10px" }}>
            <button onClick={() => setSelectedState(state.name)}>
              {state.name}
            </button>

            {selectedState === state.name && (
              <ul style={{ marginTop: "5px" }}>
                {state.counties.map((county) => (
                  <li key={county}>{county}</li>
                ))}
              </ul>
            )}
          </li>
        ))}
      </ul>

      {selectedState && (
        <button onClick={() => setSelectedState(null)} style={{ marginTop: "20px" }}>
          Hide Details
        </button>
      )}
    </div>
  );
}

export default ElectionDashboard;

This example shows how to toggle the visibility of detailed data dynamically based on user interaction.

Tips from My Experience

  • Use state to control visibility for better React integration.
  • Avoid manipulating the DOM directly (e.g., document.getElementById) — it breaks React’s declarative model.
  • Use CSS display toggling if you want to preserve component state but hide it visually.
  • Keep your UI responsive by minimizing unnecessary re-renders.
  • For complex UI, consider animation libraries like React Transition Group to animate show/hide transitions smoothly.

Showing and hiding components in React is fundamental for building dynamic, interactive web applications. Whether you use state-driven conditional rendering or CSS display toggling, the key is to keep your code readable and maintainable.

With these methods, you can easily control your UI elements and enhance user experience. If you’re new to React or want to polish your skills, practicing these techniques will take you a long way.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.