Sub topic 9
Extending native element props
This chapter assumes you can write a typed function component with a props interface, you know how ReactNode types children, and you have seen React's event types such as ChangeEvent<HTMLInputElement>. It builds on those to show how a wrapper component accepts everything the underlying DOM element accepts, plus its own props.
The problem: wrappers hide native attributes
Design systems wrap native elements. A Button adds a variant, an Input adds a label, and so on. If you type only your own props, the wrapper silently drops everything else:
interface ButtonProps {
variant?: "primary" | "secondary";
children: React.ReactNode;
}
function Button({ variant = "primary", children }: ButtonProps) {
return <button className={`btn btn-${variant}`}>{children}</button>;
}
// Error: Property 'disabled' does not exist on type 'ButtonProps'.
// <Button disabled>Save</Button>You could add disabled, onClick, type, aria-label, and form one at a time, but that list never ends. Instead, borrow the full attribute list from React's own types.
Borrowing props with ComponentPropsWithoutRef
React's type definitions can give you the props of any intrinsic element (a built-in tag such as button) from its tag name:
import type { ComponentPropsWithoutRef } from "react";
type ButtonProps = ComponentPropsWithoutRef<"button"> & {
variant?: "primary" | "secondary";
};
export function Button({ variant = "primary", className, ...rest }: ButtonProps) {
return (
<button className={`btn btn-${variant} ${className ?? ""}`} {...rest} />
);
}ComponentPropsWithoutRef<"button"> is every attribute a <button> accepts. That includes disabled, type, onClick (already typed as a handler for HTMLButtonElement), aria-* attributes, and children. The intersection (&) adds your own variant.
The component does three things:
- It destructures the props it handles itself (
variant,className). - It collects everything else in
rest. - It spreads
restonto the element.
Callers now get full checking:
<Button variant="secondary" disabled aria-label="Save" onClick={(e) => {
console.log(e.currentTarget.disabled); // e is MouseEvent<HTMLButtonElement>
}}>
Save
</Button>
// Error: Type '"danger"' is not assignable to type '"primary" | "secondary" | undefined'.
// <Button variant="danger">Delete</Button>The diagram shows how the pieces flow.
Which utility type to use
React offers several ways to name the same props. They differ in how they treat ref.
| Type | Includes `ref`? | When to use it |
|---|---|---|
| `ComponentPropsWithoutRef<"button">` | No | Default choice for wrappers |
| `ComponentPropsWithRef<"button">` | Yes | Rarely written by hand |
| `ComponentProps<"button">` | Yes | Props of an element or component when you also want its ref |
| `ButtonHTMLAttributes<HTMLButtonElement>` | No | Older code; `ComponentPropsWithoutRef` covers the same ground |
Prefer ComponentPropsWithoutRef for a plain function component. A function component cannot receive ref as a normal prop in React 18 and earlier, so a type that advertises ref promises something the component does not deliver. Callers could pass a ref and it would be ignored with a warning. Forwarding refs is covered in a later chapter, where you will use forwardRef to make that promise real.
You can also take props from another component instead of a tag name:
import type { ComponentPropsWithoutRef } from "react";
import { Button } from "./Button";
type IconButtonProps = ComponentPropsWithoutRef<typeof Button> & {
icon: string;
};typeof Button is the type of the component function, so IconButtonProps always tracks Button's current props.
Interface or intersection?
Both work. interface ... extends also accepts the borrowed type, because it resolves to an object type with known members:
import type { ComponentPropsWithoutRef } from "react";
interface ButtonProps extends ComponentPropsWithoutRef<"button"> {
variant?: "primary" | "secondary";
}The difference shows up when a custom prop has the same name as a native one.
- Interface
extendsreports an error at the declaration if your property type is not compatible with the native one. You find out immediately. - Intersection never reports an error at the declaration. It combines both property types. If they do not overlap, the result is
never(or justundefinedfor an optional prop), and callers hit confusing errors later.
The <input> element has a native size prop, which is a number. Suppose you want size="sm" | "lg":
import type { ComponentPropsWithoutRef } from "react";
// No error here, but size is now effectively unusable:
// number & ("sm" | "lg") is never, so only undefined remains.
type BrokenInputProps = ComponentPropsWithoutRef<"input"> & {
size?: "sm" | "lg";
};Remove the native property first with Omit, then add yours:
import type { ComponentPropsWithoutRef } from "react";
type InputProps = Omit<ComponentPropsWithoutRef<"input">, "size"> & {
label: string;
size?: "sm" | "lg";
};
export function Field({
label,
size = "sm",
id,
className,
...rest
}: InputProps) {
return (
<label htmlFor={id}>
{label}
<input
id={id}
className={`field field-${size} ${className ?? ""}`}
{...rest}
/>
</label>
);
}Because size and label are destructured, rest contains only attributes that are valid on <input>. If you forgot to destructure size, TypeScript would report an error at the spread, since "sm" | "lg" is not a valid native size.
Use Omit on any prop you redefine. ComponentPropsWithoutRef<"input"> is a plain object type, so Omit behaves as you expect here. Be careful with Omit on large union types, because it collapses unions into one object type.
Spread order decides who wins
When you spread rest onto an element, the order of attributes matters at runtime. Later attributes override earlier ones.
// Caller can override type, because rest comes last.
<button type="button" {...rest} />
// Caller cannot override type, because yours comes last.
<button {...rest} type="button" />Choose deliberately. A default such as type="button" (which prevents accidental form submission) should usually come before {...rest}, so a caller can still pass type="submit". A value that the component must control, such as a computed aria-disabled, goes after.
Props that combine instead of override need manual handling. className is the common case: if you leave it inside rest and also set className on the element, one of them wins and the other is lost. That is why the earlier examples destructure className and merge it. The same applies to style and to event handlers such as onClick, when your component needs to run its own logic and the caller's.
import type { ComponentPropsWithoutRef, MouseEvent } from "react";
type TrackedButtonProps = ComponentPropsWithoutRef<"button">;
export function TrackedButton({ onClick, ...rest }: TrackedButtonProps) {
function handleClick(e: MouseEvent<HTMLButtonElement>) {
console.log("clicked");
onClick?.(e);
}
return <button {...rest} onClick={handleClick} />;
}onClick is optional in the native props, so call it with ?.. The parameter type of your handler must match what the native prop expects, which is MouseEvent<HTMLButtonElement> here.
Common errors
- Using
ComponentProps<"button">and then ignoringref. The type allows arefprop that the function never receives. Switch toComponentPropsWithoutRef. - Redefining a native prop with an intersection. The prop becomes
never. UseOmitor aninterface extends. - Forgetting to destructure a custom prop. It lands in
restand is spread to the DOM, which React warns about as an unknown attribute. - Typing the element wrong.
ComponentPropsWithoutRef<"div">on a component that renders a<section>accepts props the element may not support. Match the tag you actually render. - Hand-typing
onClickas() => void. This narrows what callers can pass and loses the event parameter. Inherit the native type instead.
Exercise
You write type CardProps = ComponentPropsWithoutRef<"div"> & { title: string } and render <div {...rest}>. A teammate reports that <Card title="Hello" /> shows a tooltip over the whole card. Why does this happen, and how do you fix both the types and the component?
Show answer
The native <div> already has a title attribute, a string that browsers show as a tooltip. The intersection is compatible (string & string), so TypeScript reports no error. Because title is not destructured, it stays in rest and is spread onto the div. Fix it in one of two ways: rename the custom prop (for example heading) and destructure it, or keep the name, use Omit<ComponentPropsWithoutRef<"div">, "title"> in the type, destructure title, and render it inside an <h2>.
Exercise
Write the props type for a Select wrapper around <select> that adds a required label: string, and replaces the native onChange with onValueChange: (value: string) => void. Which utility types do you need?
Show answer
type SelectProps = Omit<ComponentPropsWithoutRef<"select">, "onChange"> & { label: string; onValueChange: (value: string) => void };. ComponentPropsWithoutRef<"select"> supplies the native attributes, and Omit removes onChange so the component owns that behavior. Inside, destructure label and onValueChange, and render <select {...rest} onChange={(e) => onValueChange(e.target.value)}>.