React Foundations · TypeScript

Typing children

Typing children

A wrapper component is handed whatever you nest between its tags. In TypeScript that content is the children prop, and its type is ReactNode — the union of everything React can render: elements, strings, numbers, null, and arrays of them.

import type { ReactNode } from 'react';

interface CardProps {
  title: string;
  children: ReactNode;
}

Writing children: ReactNode in the interface accepts any renderable content and rejects what React cannot draw. PropsWithChildren<CardProps> is the same thing without repeating the field: it adds children: ReactNode to whatever props you pass it.

function Card({ title, children }: PropsWithChildren<CardProps>) {
  return (
    <section>
      <h2>{title}</h2>
      {children}
    </section>
  );
}

Now the wrapper owns its structure and the caller owns the inside, with both sides typed. Pass a wrong child — an object, say — and the compiler stops it at the call site.

Your job is to type a wrapper's children in App.tsx.

Challenge

A wrapper drops whatever you put inside it. Export an App component from App.tsx that renders a Card with title="Hello" wrapping a paragraph reading World. Card takes PropsWithChildren<{ title: string }> and renders its children inside a <section> next to the title.

The Test renders your component and looks for that paragraph inside the section. The starter renders an empty section and ignores its children, so the Test fails.

App.tsx
export function App() {
  return (
    <section>
      <h2>Hello</h2>
    </section>
  );
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.