Given a component that takes custom props as well as html attribute props, how should the interface for such a component be created? Ideally, the interface would also handle react-specific html props such as using className
instead of class
.
This is the usage example for which I am trying to find the right interface:
<MyComponent customProp='value' style={{textAlign: 'center'}} />
All Supported HTML AttributesAs of React 16, any standard or custom DOM attributes are fully supported. These props work similarly to the corresponding HTML attributes, with the exception of the special cases documented above. You may also use custom attributes as long as they're fully lowercase.
By default, React does not permit you to inject HTML in a component, for various reasons including cross-site scripting. However, for some cases like a CMS or WYSIWYG editor, you have to deal with raw HTML.
React props can be accessed as an object or destructured Props can be accessed as an entire object which is usually called "props". Or they can be destructured, since props will always be an object, into separate variables.
Props are arguments passed into React components. Props are passed to components via HTML attributes. props stands for properties.
interface IMyComponentProps extends React.HTMLAttributes<HTMLElement> { customProp: string; }
UPD: @ddek mentioned intersections &
.
I would like to warn you about the following issue with that approach.
interface A { onClick: () => void; } interface B { onClick: (event: React.MouseEvent<HTMLElement>) => void; } // Typescript does not complain. This is not good type AB = A & B; const a: AB = { onClick: () => {} }; // TS2320: Interface 'AB2' cannot simultaneously extend types 'A' and 'B'. // Named property 'onClick' of types 'A' and 'B' are not identical. interface AB2 extends A, B { } // TS2430: Interface 'AC' incorrectly extends interface 'A'. // Types of property 'onClick' are incompatible. // Type '(event: MouseEvent<HTMLElement, MouseEvent>) => void' is not // assignable to type '() => void'. interface AC extends A { onClick: (event: React.MouseEvent<HTMLElement>) => void; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With