I am creating React components in TypeScript and type hinting the props like such:
export interface ExampleProps {
someProp: string,
anotherProp: React.ReactNode
}
export default function Example({
someProp,
...props
}: ExampleProps) {
return (
<div {...props}>...</div>
);
}
I would like to also pass on standard React/HTML props like className
, children
, style
, id
, title
, lang
, etc... without having to explicitly write out all of them. So I can do something like:
<Example className="some-class" someProp="value" anotherProp={<div></div>}>Content</Example>
I would have thought that it should be possible to extend an interface for this like:
export interface ExampleProps extends PropsWithChildren {
someProp: string,
anotherProp: React.ReactNode
}
But this complains: Generic type 'PropsWithChildren' requires 1 type argument(s)
export interface ExampleProps extends PropsWithChildren<typeof Example> {
someProp: string,
anotherProp: React.ReactNode
}
But this complains, Type { children: string; className: string; someProp: string, anotherProp: Element }' is not assignable to type 'IntrinsicAttributes & SlotsProps
Then I tried:
export interface ExampleProps extends PropsWithChildren<{}> {
someProp: string,
anotherProp: React.ReactNode
}
But this complains, Property 'className' does not exist on type 'IntrinsicAttributes & SlotsProps'
, since apparently all that PropsWithChildren contains is children.
So I also tried replacing PropsWithChildren
with ComponentProps
and ElementType
but this didn't help either.
Does React not maintain a list of standard props that apply to all elements?
You can and should indeed use the extends
:
export interface ExampleProps extends React.HTMLAttributes<HTMLDivElement> {
someProp: string;
}
export default function Example({ someProp, ...restProps }: ExampleProps) {
return <div {...restProps} />;
}
Depending on your IDE, you can actually click or hover the element you want and read it's type.