reactjs - Crear elemento React dinámicamente en Typescript
Estoy intentando crear un elemento en React con TypeScript basado en el tagName pasado como props, y quiero añadir propiedades de elemento relativas basadas en ese tagName. Aquí está mi código.
type ElementProps<Tag extends keyof JSX.IntrinsicElements> =
JSX.IntrinsicElements[Tag];
type Props = {
tagName?: React.ComponentType | keyof JSX.IntrinsicElements;
};
const Editable: React.FC<Props> = ({
tagName = 'div',
...props
}) => {
const htmlEl = useRef(null);
const elementProps: ElementProps<typeof tagName> = {
...props,
ref: htmlEl,
};
return createElement(tagName, elementProps, children);
};
Estoy recibiendo este error
Type 'keyof IntrinsicElements | ComponentType<{}>' does not satisfy the constraint 'keyof IntrinsicElements'.
Type 'ComponentClass<{}, any>' is not assignable to type 'keyof IntrinsicElements'.
Type 'ComponentClass<{}, any>' is not assignable to type '"view"'
Respuesta #1
Estuviste cerca.
ElementProps espera una cadena - keyof JSX.IntrinsicElements aunque typeof tagName podría ser un ComponentType<{}.
Todo lo que necesitas hacer es mover la restricción de tipo dentro de una utilidad de tipo.
import React, { useRef, createElement } from "react";
type ElementProps<Tag> =
Tag extends keyof JSX.IntrinsicElements
? JSX.IntrinsicElements[Tag]
: never
type Props = {
tagName?: React.ComponentType | keyof JSX.IntrinsicElements;
};
const Editable: React.FC<Props> = ({
tagName = 'div',
...props
}) => {
const htmlEl = useRef(null);
const elementProps: ElementProps<typeof tagName> = {
...props,
ref: htmlEl,
};
return createElement(tagName, elementProps);
};
Parque infantil
Me preguntaba si podría obtener los únicos detalles de las propiedades con respecto a la etiqueta que pasó en el nombre de la etiqueta?
Claro, es posible.
import React, { useRef, createElement } from "react";
type ElementProps<Tag> = Tag extends keyof JSX.IntrinsicElements
? JSX.IntrinsicElements[Tag]
: never;
type Values<T> = T[keyof T];
type ObtainHTMLProps<T extends Values<JSX.IntrinsicElements>> =
T extends React.DetailedHTMLProps<infer Props, HTMLElement> ? Props : never;
type AllowedProps = Values<{
[Tag in keyof JSX.IntrinsicElements]: {
tagName: Tag;
} & ObtainHTMLProps<JSX.IntrinsicElements[Tag]>;
}>;
const Editable: React.FC<AllowedProps> = ({ tagName = "div", ...props }) => {
const htmlEl = useRef(null);
const elementProps: ElementProps<typeof tagName> = {
...props,
ref: htmlEl,
};
return createElement(tagName, elementProps);
};
const canvas = <Editable tagName="canvas" width={20} /> // ok
const anchor = <Editable tagName="a" href={'www.example.com'} /> // ok
const invalid = <Editable tagName="canvas" href={'www.example.com'} /> // expected error
Consulta los tipos de React node_modules\@typeseact\index.d.ts. Ahí encontrarás IntrinsicElements
Teniendo tagName puedes inferir fácilmente el primer argumento de DetailedHTMLProps. Consulta ObtainHTMLProps.
Ahora, necesitas crear una unión de todos los atributos permitidos y es un número finito de props. Mira AllowedProps.
