Capítulo 86 de 116

Chapter 86: isValidElement

Core Idea

isValidElement(value) checks whether a given value is a React element (something created by JSX or createElement) — a type guard mainly useful in generic/library code that needs to branch on "is this JSX or just arbitrary data."

Key Concepts

  • Signature: isValidElement(value) returns a boolean — true for anything produced by JSX/createElement, false for plain objects, strings, numbers, arrays, or anything else that isn't a React element.
  • Typical use case: utility/library code that accepts a prop which might be either a React element or plain data (e.g. a string label vs. a custom JSX icon) and needs to render each differently based on which one it received.
  • Not a component-instance check: it validates the element description (the lightweight object from Ch 81), not whether something is mounted, rendered, or a particular component type — it doesn't tell you which component an element is, only that it is one.
  • Rarely needed in typical application code — mostly relevant when writing flexible, generic components/utilities (similar territory to Children, Ch 77) that need to handle heterogeneous inputs safely.

Code Examples

function Label({ content }) {
  return isValidElement(content) ? content : <span>{content}</span>;
}
  • What it demonstrates: a prop that could be either a plain string or a custom JSX element, rendered appropriately either way.

Key Takeaways

  1. Reach for this in generic/utility components that need to accept "either JSX or plain data" as a prop — not in typical feature code.
  2. It answers "is this a React element at all," not "is this a specific component type" — pair with other checks if you need type-specific branching.
  3. It operates on the lightweight element-description object (Ch 81), unrelated to rendering/mounting state.

Connects To

  • Ch 81 (createElement): the element-creation mechanism this function validates against.
  • Ch 77 (Children): similar generic-component-authoring territory.