Last updated: Feb 29, 2024
Reading time·2 min
To extend an HTML Element in a component's props in React, extend the specific element type in the props interface of your component.
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.
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.
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.
children
prop to the componentIf 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
.
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.
I've also written a detailed guide on how to use create-react-app with TypeScript.