Necesito un accesorio React para tratar con todos los atributos html posibles de un elemento div HTML que forma parte de un componente React, pero tengo un problema con el rigor de Typescript frente a las posibilidades de React.
Aquí el componente:
import React from 'react' type DivAttrs = { container?: React.HTMLAttributes<HTMLDivElement> } ... <div {...divAttributes?.container}>Y aquí la prop const proporcionada al componente:
const divAttributes: DivAttrs = { container: { 'aria-describedby': 'test', 'data-custom-attribute': 'test', 'data-random-attribute': 'test', id: 'test' } } Los accesorios data-custom-attribute y data-random-attribute dan estos errores
(property) 'data-custom-attribute': string Type '{ 'aria-describedby': string; 'data-custom-attribute': string; 'data-random-attribute': string; id: string; }' is not assignable to type 'HTMLAttributes<HTMLDivElement>'. Object literal may only specify known properties, and ''data-custom-attribute'' does not exist in type 'HTMLAttributes<HTMLDivElement>'.(2322)¿Cuál sería la solución perfecta para solucionar este problema? Muchas gracias
Las propiedades data-custom-attribute y data-random-attribute no existen en el tipo React.HTMLAttributes , por lo que no podrá usarlo. Además, data-custom-attribute y data-random-attribute no se utilizan en ningún elemento HTML, por lo tanto, su mejor apuesta sería combinar el tipo React.HTMLAttributes existente (para seguir teniendo acceso a los atributos de elemento HTMLDivElement comunes) con sus propios CustomAttrs para poder usar unos específicos para su caso de uso:
interface CustomAttrs { 'data-custom-attribute': string; 'data-random-attribute': string; } type DivAttrs = { container?: React.HTMLAttributes<HTMLDivElement> & CustomAttrs, }