How to show and hide data based on condition in React?

Control visibility of elements in React using conditional rendering and state toggling.

beginnerConditional renderingreactconditional renderingstateui toggle
Published: 10/26/2025
Updated: 10/26/2025

Question

How to show and hide data based on condition in React?


Answer

Use a state variable and conditional rendering.

import { useState } from 'react';

function ToggleData() {
  const [show, setShow] = useState(false);

  return (
    <div>
      <button onClick={() => setShow(!show)}>
        {show ? 'Hide Data' : 'Show Data'}
      </button>

      {show && <p>This is some conditional data!</p>}
    </div>
  );
}

âś… How it works:

  • show tracks visibility.
  • When the button is clicked, the value toggles.
  • React re-renders, and {show && <p>...</p>} controls visibility.

Real-World Example

  • Show/hide a modal or sidebar.
  • Expand/collapse FAQ answers.
  • Toggle loading or error messages.

Quick Practice

Build a component that shows and hides a user’s profile card when a button is clicked.

Summary

Use useState + conditional rendering to control what appears on screen.

Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions

What’s the simplest way to show or hide content?

Use state with conditional rendering. Example: `{isVisible && <div>...</div>}`

Should I use CSS for show/hide?

If performance or animation matters, you can toggle a CSS class instead.


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.