Type Safety with JSX Props
You'll learn how to correctly type props that accept JSX content in TypeScript, ensuring consumers pass valid renderable elements.
The Core Idea
When you design a component that accepts JSX as props (like header={<h1>Title</h1>}), TypeScript needs to know what types are acceptable. Unlike string or number props, JSX content has special types in React's type system. Using the wrong type can lead to confusing errors or allow invalid content to slip through.
The Right Types for JSX Props
React provides two main types for JSX content:
ReactNode – The broadest type, accepts anything React can render: JSX elements, strings, numbers, arrays, fragments, null, undefined, and booleans. This is your go-to for most slot props.
ReactElement – Stricter, only accepts actual JSX elements (the result of <Component />). Use this when you need specifically an element, not primitives.
import { ReactNode, ReactElement } from 'react';
interface CardProps {
header: ReactNode; // Flexible: accepts <h1>Title</h1> or "Title"
footer: ReactElement; // Strict: must be <Footer /> not "text"
}
function Card({ header, footer }: CardProps) {
return (
<div>
<header>{header}</header>
<footer>{footer}</footer>
</div>
);
}
Optional Slots
Make JSX props optional with ? and handle their absence:
interface LayoutProps {
sidebar?: ReactNode;
content: ReactNode;
}
function Layout({ sidebar, content }: LayoutProps) {
return (
<div>
{sidebar && <aside>{sidebar}</aside>}
<main>{content}</main>
</div>
);
}
Key Takeaway: Use ReactNode for flexible JSX props that accept any renderable content, and ReactElement when you need specifically a JSX element—this prevents runtime errors and provides better IDE autocomplete.