Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React with TypeScript: Generic Components, PropsWithChildren, and Event Types

Generic props that infer from data, PropsWithChildren instead of React.FC, and element-scoped event types that keep currentTarget typed.

~4 min readReact
#React#TypeScript#Components
3D illustration of type-safe generic React component blocks snapping tightly together with typed DOM event handlers

Quick Summary

A generic React component is a function that infers the type of its data from the props you pass. <List items={users} render={(u) => u.name} /> infers T = User without an annotation, which means the render prop is checked against the actual element type rather than against unknown or any. Generics make reusable components type-safe; they do not make them accept more inputs.

Two type helpers cover most of the rest. PropsWithChildren<P> adds an optional children?: ReactNode to a props type, which is the explicit alternative to React.FC — and since React 18's types removed the implicit children from React.FC, the helper is now the normal way to declare it. ComponentProps<"button"> reuses the platform's own prop types, including onClick, disabled, and aria-*, instead of re-declaring a subset by hand.

Event typing is where most of the friction lives. React does not pass native events to handlers: it passes synthetic events whose currentTarget is typed to the element the handler was attached to, while target stays the looser EventTarget. That is why e.currentTarget.value type-checks on an <input> handler and e.target.value does not, and why annotating a handler with the DOM's MouseEvent instead of React.MouseEvent compiles but loses the React-specific fields.

Basic Syntax & Signature

tsx
import type { ReactNode, PropsWithChildren, ComponentProps, ChangeEvent } from "react"; // Generic component: T is inferred from `items`. type ListProps<T> = { items: readonly T[]; render: (item: T, index: number) => ReactNode; keyOf: (item: T) => string; }; function List<T>({ items, render, keyOf }: ListProps<T>) { return <ul>{items.map((item, i) => <li key={keyOf(item)}>{render(item, i)}</li>)}</ul>; } const users = [{ id: "u1", name: "Ada" }]; const el = <List items={users} render={(u) => u.name} keyOf={(u) => u.id} />; // PropsWithChildren adds children?: ReactNode. type CardProps = PropsWithChildren<{ title: string; tone?: "info" | "warn" }>; function Card({ title, tone = "info", children }: CardProps) { return ( <section data-tone={tone}> <h2>{title}</h2> {children} </section> ); } // ComponentProps borrows the platform's types, including ref when asked. type IconButtonProps = ComponentProps<"button"> & { icon: ReactNode }; function IconButton({ icon, ...rest }: IconButtonProps) { return <button type="button" {...rest}>{icon}</button>; } // Typed events: element-specific, and currentTarget is the typed element. function Search({ onSearch }: { onSearch: (value: string) => void }) { function onChange(e: ChangeEvent<HTMLInputElement>) { onSearch(e.currentTarget.value); } return <input onChange={onChange} aria-label="search" />; }

In a .tsx file, a generic arrow component needs a trailing comma or an extends clause to disambiguate it from JSX:

tsx
const Row = <T,>({ item }: { item: T }) => <div>{String(item)}</div>; const Row2 = <T extends unknown>({ item }: { item: T }) => <div>{String(item)}</div>;

Key Comparison Table

Type expressionChildren includedRef includedBest for
{ title: string }NoNoPlain props
PropsWithChildren<{ title: string }>Yes, optionalNoLayout and container components
React.FC<Props>No, since React 18 typesNoDiscouraged: no benefit over a function
React.FC<PropsWithChildren<Props>>YesNoLegacy codebases
ComponentProps<"input">NoNoWrapping a DOM element
ComponentPropsWithRef<"input">NoYesWrappers that forward ref
ReactNodeNot applicableNot applicableReturn type of a component
JSX.ElementNot applicableNot applicableOlder code; narrower than ReactNode

Practical Edge Cases & Deep Dives

1. Inference breaking when a generic is only in the return type

tsx
// Wrong: T cannot be inferred from props, so callers must annotate it. function useToggle<T>(): [T | undefined, (next: T) => void] { const [value, setValue] = useState<T | undefined>(undefined); return [value, setValue]; } const [v, setV] = useToggle<string>(); // annotation required // Right: a default keeps inference useful and the call site clean. function useToggle<T = boolean>(): [T | undefined, (next: T) => void] { const [value, setValue] = useState<T | undefined>(undefined); return [value, setValue]; } const [flag, setFlag] = useToggle(); // T = boolean

A type parameter that appears only in the output cannot be inferred from an argument, so it falls back to unknown. Defaults are the fix; explicit instantiation is the fallback.

2. Generic components with a constrained element type

tsx
type SelectProps<T extends { id: string; label: string }> = { options: T[]; value: T | null; onChange: (next: T) => void; }; function Select<T extends { id: string; label: string }>({ options, value, onChange }: SelectProps<T>) { return ( <select value={value?.id ?? ""} onChange={(e) => { const next = options.find((o) => o.id === e.currentTarget.value); if (next) onChange(next); }} > <option value="">Select…</option> {options.map((o) => <option key={o.id} value={o.id}>{o.label}</option>)} </select> ); }

The constraint gives the component the properties it needs (id, label) while preserving the caller's extra fields on onChange. Without the constraint, T could be a string and the body would not compile; with it, the items stay fully typed at the call site.

3. as props without losing type safety

tsx
type BoxProps<T extends React.ElementType> = { as?: T; children?: ReactNode; } & Omit<ComponentPropsWithRef<T>, "as" | "children">; function Box<T extends React.ElementType = "div">({ as, children, ...rest }: BoxProps<T>) { const Tag = (as ?? "div") as React.ElementType; return <Tag {...rest}>{children}</Tag>; } // Renders an <a>; href is type-checked against ComponentProps<"a">. const link = <Box as="a" href="/docs">Docs</Box>;

The Omit removes as and children from the inherited props so they cannot collide with the polymorphic ones. ComponentPropsWithRef<T> in React 19 includes ref as a normal prop, which is what lets the polymorphic component forward it without a cast at the call site.

4. Event handler types for every element

tsx
function Form() { const onSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); const data = new FormData(e.currentTarget); console.log(data.get("email")); }; const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === "Enter" && !e.shiftKey) e.currentTarget.blur(); }; const onMouseEnter = (e: React.MouseEvent<HTMLButtonElement>) => { console.log(e.clientX, e.currentTarget.name); }; return ( <form onSubmit={onSubmit}> <input name="email" onKeyDown={onKeyDown} /> <button name="send" onMouseEnter={onMouseEnter}>Send</button> </form> ); }

React.FormEvent does not have currentTarget.value: the form is not an input. React.ChangeEvent<HTMLInputElement> is the one that carries value, and the element parameter is what gives currentTarget its type — React.MouseEvent without the parameter types currentTarget as EventTarget.

5. Passing handlers to a reusable component

tsx
type ButtonProps = { onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void; children: ReactNode; } & Omit<ComponentProps<"button">, "onClick" | "children">; function Button({ onClick, children, ...rest }: ButtonProps) { return ( <button type="button" onClick={onClick} {...rest}> {children} </button> ); }

Declaring the handler inline and also spreading ComponentProps<"button"> produces an intersection of two onClick types, which TypeScript resolves to an overloaded, effectively unusable signature. Omit the keys you are re-declaring, then spread the rest.

6. React.FC vs a plain function

tsx
// React.FC: no children unless declared, and no generic parameter support. const OldTitle: React.FC<{ text: string }> = ({ text, children }) => ( // error <h1>{text}{children}</h1> ); // Plain function with an explicit props type: same result, no wrapper. function Title({ text }: { text: string }) { return <h1>{text}</h1>; }

React.FC adds nothing a plain annotated function lacks — it once implied children, but React 18's types removed that. It also cannot express a generic component without an extra function expression. The one thing it does add is a children property in old codebases that relied on it, which is the reason the helper exists at all.

Common Compilation/Runtime Mistakes

SymptomCauseFix
'value' does not exist on type 'EventTarget'e.target used instead of e.currentTargete.currentTarget.value
Handler type mismatch on onChangeAnnotated as React.MouseEventReact.ChangeEvent<HTMLInputElement>
children is not a valid propReact.FC in React 18+ typesPropsWithChildren<P>
JSX element type 'T' does not have any construct or call signaturesGeneric treated as a componentConstrain to React.ElementType or ComponentType
onClick cannot be calledIntersection of two handler typesOmit the re-declared keys
Props spread with ref reaches the DOMUnaudited spread on a React 19 componentDestructure ref or use ComponentPropsWithRef
<T> parsed as JSX in .tsxArrow generic ambiguity<T,> or <T extends unknown>
ReactNode returned from a component typed JSX.ElementNarrower return typeType the return as ReactNode
any everywhere in event handlersUnannotated parametersType the element parameter, not the event
Type errors only in the test fileDifferent JSX namespace or @types/react versionDedupe React types

TypeScript's job in a React component is to describe what the component actually accepts and where each value comes from. Generics describe reusable data shapes, PropsWithChildren describes composition, ComponentProps describes delegation to the platform, and element-scoped event types describe the one element that fired the handler. Getting those four right removes most of the casts, and the casts that remain are usually pointing at a prop that should have been a generic.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.