Adding custom HTML elements to React TypeScript
I recently created a grid system using custom HTML elements and wanted to use it in my React project, except JSX doesn’t like tags with dashes. Below is a quick solution I found.
// types/grid-container.ts
import type { DetailedHTMLProps, HTMLAttributes } from "react";
interface ContainerAttributes extends HTMLAttributes<HTMLElement> {
size?: string;
}
interface ColAttributes extends HTMLAttributes<HTMLElement> {
span?: string;
}
declare module "react/jsx-runtime" {
namespace JSX {
interface IntrinsicElements {
"grid-container": DetailedHTMLProps<ContainerAttributes, HTMLElement>;
"grid-row": DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>;
"grid-col": DetailedHTMLProps<ColAttributes, HTMLElement>;
}
}
}I create a TS file defining my custom elements, then can apply it, like so:
// Using in my components
function MyComponent() {
return (
<grid-container size="lg">
</grid-container>
);
}