Sometimes, we want to extend HTML elements in React and TypeScript while preserving props.
In this article, we’ll look at how to extend HTML elements in React and TypeScript while preserving props.
How to extend HTML elements in React and TypeScript while preserving props?
To extend HTML elements in React and TypeScript while preserving props, we can include the React.HTMLProps<HTMLButtonElement>
type in our prop type.
For instance, we write
export const Button: React.FC<
ButtonProps & React.HTMLProps<HTMLButtonElement>
> = ({ ...props, children, icon }) => (
<StyledButton {...props}>
{icon && <i className="material-icons">{icon}</i>}
{children}
</StyledButton>
);
to set the prop type of the Button
component to ButtonProps & React.HTMLProps<HTMLButtonElement>
.
ButtonProps
is the prop type that we created and React.HTMLProps<HTMLButtonElement>
is the prop type of the HTML button element.
We combine then with &
so that properties from both interfaces are valid props.
Conclusion
To extend HTML elements in React and TypeScript while preserving props, we can include the React.HTMLProps<HTMLButtonElement>
type in our prop type.