0
0
ReactHow-ToBeginner · 3 min read

How to Render Nothing in React: Simple Techniques

In React, to render nothing from a component, return null or an empty fragment <></>. Returning null tells React to render nothing in the UI for that component.
📐

Syntax

To render nothing in React, your component should return either null or an empty fragment <></>. Returning null means React will not render any DOM element for that component. An empty fragment also renders nothing but can be useful when you want to return multiple elements conditionally.

jsx
function MyComponent() {
  // Return null to render nothing
  return null;

  // Or return empty fragment to render nothing
  // return <></>;
}
Output
No output rendered in the UI
💻

Example

This example shows a component that renders a message only if showMessage is true. Otherwise, it renders nothing by returning null.

jsx
import React, { useState } from 'react';

function Message({ showMessage }) {
  if (!showMessage) {
    return null; // Render nothing
  }
  return <p>Hello! This is a message.</p>;
}

export default function App() {
  const [show, setShow] = useState(false);

  return (
    <>
      <button onClick={() => setShow(!show)}>
        {show ? 'Hide' : 'Show'} Message
      </button>
      <Message showMessage={show} />
    </>
  );
}
Output
Button labeled 'Show Message' initially; clicking it toggles the message 'Hello! This is a message.' below the button or hides it.
⚠️

Common Pitfalls

A common mistake is returning undefined or an empty string '' instead of null. React treats undefined as an error and rendering an empty string may still create an empty text node in the DOM.

Always use null or an empty fragment <></> to render nothing cleanly.

jsx
function Wrong() {
  // This will cause a warning or error
  // return undefined;

  // This renders an empty text node, not recommended
  // return '';

  // Correct way
  return null;
}
Output
No output rendered when returning null; warnings or unexpected output if returning undefined or empty string.
📊

Quick Reference

MethodDescriptionUsage
Return nullRender nothing, no DOM outputreturn null;
Return empty fragmentRender nothing, useful for multiple elementsreturn <>;
Avoid undefinedCauses errors or warningsDo not return undefined;
Avoid empty stringCreates empty text nodeDo not return '';

Key Takeaways

Return null from a React component to render nothing in the UI.
An empty fragment <> also renders nothing and can wrap multiple elements.
Never return undefined or empty string to render nothing; it causes errors or unwanted output.
Use conditional rendering with null to cleanly show or hide components.
Rendering nothing means React skips creating any DOM nodes for that component.