DEV Community

Ernesto Jara Olveda
Ernesto Jara Olveda

Posted on

Create Custom HTML Components React

This generic component is useful if you are creating your own ui library and you want your components accept not only the props you want them to have, but also all the native props. for example you want your Button component to accept and auto complete the eventHandlers, aria-props and stuff w/out specifying'em.


import React from "react";

const defaultProps = {
  tag: "section",
};

type Props = React.HTMLAttributes<HTMLElement> & typeof defaultProps & {
    tag: React.ElementType;
    className: string;
    cssModule?: CSSModule;
}

const Html: React.FC<Props> = (props) => {
    const { tag: Tag, ...attributes } = props;

    return <Tag {...attributes} className={classes} />;
};

Section.defaultProps = defaultProps;

export default Html;
Enter fullscreen mode Exit fullscreen mode

now when you create your curstom button you'll see it will accept the props you set and also the "native props"

<Html tag="button" onClick={e=>{e.preventDefault();}}/>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)