Using A Type definition For All HTML Elements
In order to allow all HTML elements to be used as your tag, you can utilize the keys of the IntrinsicElements
interface defined in the JSX
namespace. IntrinsicElements
appears to contain a mapping of HTML element tags to their respective attributes (includes element-specific attributes). To utilize these keys we can do the following:
interface Props {
tag?: keyof JSX.IntrinsicElements
}
What if I want to allow React components to be used as the tag?
React defines two interfaces: ComponentClass
and FunctionComponent
. React also defines a union of these two interfaces that allows you to specify any React component: ComponentType
. We can create a union of this and our last definition to allow both components and HTML tags.
import { ComponentType } from 'react';
interface Props {
tag?: ComponentType | keyof JSX.IntrinsicElements;
}
Well, now I have a tag, what about HTML attributes?
If you want to allow all other HTML attributes to be allowed you can either extend React.HTMLAttributes<Element>
to get all of the shared HTML attributes (no element-specific ones) or you can introduce a generic and utilize JSX.IntrinsicElements
.
The second option is more complex and comes with a few caveats. You have to use type
instead of interface
to extend/intersect your Props
and the specific attributes defined on a key in JSX.IntrinsicElements
. You will also need to use generics on your function so that you can pass them to your Props
type which means you can no longer use React.FunctionComponent<Props>
since that happens before access to any generics. This means you'll want to add children
to your Props
definition.
That was a lot of words which I believe are better explained with this example:
// Define our Props type to allow the specifying of a Tag for HTML attributes
// Also define children as React does with React.ReactNode
type Props<Tag extends keyof JSX.IntrinsicElements> = {
tag?: ComponentType | keyof JSX.IntrinsicElements;
children?: ReactNode;
} & JSX.IntrinsicElements[Tag];
// Define our generic (Tag) again here and give it our default value
// Don't forget to specify the type Props<Tag> at the end of your function's arguments
// Then we can spread all props to the tag/Wrapper
function MyComponent<Tag extends keyof JSX.IntrinsicElements = 'div'>({ tag: Wrapper = 'div', ...props }: Props<Tag>) {
return <Wrapper {...props} />;
}
// Example usage, noValidate is typed as
// (JSX attribute) React.FormHTMLAttributes<HTMLFormElement>.noValidate?: boolean | undefined
<MyComponent<'form'> tag="form" noValidate>
{/* My Form Stuff */}
</MyComponent>;
// You don't need to specify 'div' since it is the default
<MyComponent id="page">
<p>Just a paragraph inside of a regular div</p>
</MyComponent>;