Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one extend React types to support html attributes as props?

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'}}  /> 
like image 951
aryzing Avatar asked May 31 '18 15:05

aryzing


People also ask

Does React support all HTML attributes?

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.

Can I use HTML tags in React?

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.

Can React props be objects?

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.

What does props in React mean?

Props are arguments passed into React components. Props are passed to components via HTML attributes. props stands for properties.


1 Answers

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; }  
like image 103
Yozi Avatar answered Sep 20 '22 10:09

Yozi