Extend an HTML Element in a Component's props in React (TS)

avatar

Borislav Hadzhiev

Sun Apr 17 20222 min read

banner

Photo by Anthony Tran

Extend an HTML Element in a Component's props in React (TS) #

To extend an HTML Element in a component's props in React, extend the specific element type in the props interface of your component, e.g. interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {}.

App.tsx
import React from 'react'; interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { text: string; children?: React.ReactNode; // ... your custom props here } const Button: React.FunctionComponent<ButtonProps> = ({text, ...rest}) => { return <button {...rest}>{text}</button>; }; const App = () => { return ( <div> <Button onClick={() => console.log('button clicked')} text="Click" /> </div> ); }; export default App;

We used the React.ButtonHTMLAttributes type to extend a button element in the component's props.

You can add your custom props in the interface and your component can be passed any of the element-specific props.

The Button component can be passed any button-specific props in the example.

If you need a more broad type, you can use the HTMLAttributes type instead.

Other commonly used types to extend from are InputHTMLAttributes, TextareaHTMLAttributes, LabelHTMLAttributes, SelectHTMLAttributes, AnchorHTMLAttributes, CanvasHTMLAttributes, FormHTMLAttributes, ImgHTMLAttributes, etc.

Notice that we passed the HTMLButtonElement type to the ButtonHTMLAttributes generic in the example.

You might be extending an element of a different type.

The types are consistently named as HTML***Element. Once you start typing HTML.., your IDE should be able to help you with autocomplete.

Some commonly used types are: HTMLInputElement, HTMLButtonElement, HTMLAnchorElement, HTMLImageElement, HTMLTextAreaElement, HTMLSelectElement, etc.

If you need to pass a children prop to the component that extends the HTML element, make sure to type the children prop as React.ReactNode.

App.tsx
import React from 'react'; interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { children?: React.ReactNode; // ... your custom props here } const Button: React.FunctionComponent<ButtonProps> = ({children, ...rest}) => { return <button {...rest}>{children}</button>; }; const App = () => { return ( <div> <Button onClick={() => console.log('button clicked')}> <p>Click</p> <p>Me</p> </Button> </div> ); }; export default App;

We typed the children prop of the Button component as React.ReactNode, so the component can be passed any button-specific props and a children prop.

You can define all of your custom props in the ButtonProps interface.

Use the search field on my Home Page to filter through my more than 1,000 articles.