Sub topic 9
Extending Native Element Props
This chapter assumes you can write function components in TSX, know TypeScript interfaces, type aliases, and intersections, and have strict mode on as set up earlier in this tutorial.
Why extend native props
A wrapper component such as Button or TextInput should accept everything its native element accepts: disabled, type, aria-* attributes, onClick, and so on. Listing each one by hand is tedious and drifts out of date. Instead, you borrow the native element's prop types and add only what is new.
Borrowing props with ComponentPropsWithoutRef
React's ComponentPropsWithoutRef<"button"> is the type of all props a <button> accepts, minus ref. You pass the tag name as a string literal.
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} />
);
}The intersection (&) combines the native props with your own variant. Three details matter here:
classNameis destructured so you can merge it with your own classes. It is optional, so it may beundefined, which is why the code uses?? ""....restcollects everything else, and spreading it onto<button>passes the native props through.variantis removed fromrestby destructuring. If you left it in, React would try to put an unknownvariantattribute on the DOM element.
Callers now get full checking:
<Button variant="secondary" disabled onClick={(e) => console.log(e.currentTarget.name)} />
<Button type="submit" aria-label="Save" />
<Button variant="danger" />The first two compile. The third fails because "danger" is not in the variant union. In the first line, e is inferred as a mouse event on a button element, so e.currentTarget.name is typed with no annotation from you.
Which helper type to use
React offers three similar types. They differ in how they treat ref.
| Type | Includes `ref` | Typical use |
|---|---|---|
| `ComponentPropsWithoutRef<"button">` | No | Function components that do not forward a ref |
| `ComponentPropsWithRef<"button">` | Yes | Components that receive a ref as a prop |
| `ComponentProps<"button">` | Yes, for intrinsic elements | Quick one-off types |
Prefer ComponentPropsWithoutRef by default. A plain function component cannot receive ref as a normal prop in many React versions, so including it in the type promises something the component cannot deliver. The last chapter in this tutorial covers forwardRef, where this distinction pays off.
Overriding a native prop
An intersection does not replace conflicting members. It combines them. If you want a different type for a prop the native element already has, remove the native one first with Omit.
import type { ComponentPropsWithoutRef } from "react";
type NumberInputProps = Omit<ComponentPropsWithoutRef<"input">, "value" | "onChange" | "type"> & {
value: number;
onChange: (value: number) => void;
};
export function NumberInput({ value, onChange, ...rest }: NumberInputProps) {
return (
<input
{...rest}
type="number"
value={value}
onChange={(e) => onChange(e.target.valueAsNumber)}
/>
);
}Without Omit, onChange would have to satisfy both the native handler type and your (value: number) => void, and almost nothing satisfies both. Omitting type also stops callers from turning the field into a checkbox.
Place {...rest} before your fixed props, as above. Props written after the spread win, so a caller cannot override type="number".
Common errors
- Spreading custom props onto the DOM. Forgetting to destructure a custom prop sends it to the element, and React warns about an unknown attribute.
- Using
interfacewith an intersection-style base.interface ButtonProps extends ComponentPropsWithoutRef<"button">also works, and it reports conflicts as errors. An intersection with a conflicting member silently producesneverfor that member. - Overwriting
classNameorstyle. Spreadingrestafter your ownclassNamereplaces yours. Destructure and merge instead.
Review
Exercise
You write type FancyInputProps = ComponentPropsWithoutRef<"input"> & { onChange: (value: string) => void }. Callers then find they cannot pass a working onChange. Why does this happen, and how do you fix it?
Show answer
The native onChange takes a change event, and the intersection requires onChange to satisfy both that type and (value: string) => void. Almost no function can do both. Fix it by removing the native prop first: Omit<ComponentPropsWithoutRef<"input">, "onChange"> & { onChange: (value: string) => void }.
Exercise
In Button, why is variant destructured in the parameter list instead of read from rest?
Show answer
Destructuring removes variant from rest. Otherwise {...rest} would pass variant to the DOM <button>, and React would warn about an unknown attribute.