Home > other >  React Typescript on dynamic component
React Typescript on dynamic component

Time:09-03

Using React with typescript I want to be able to create a dynamic component. Here is snapshot from code

const CustomTag = `${section.header_type}`;
<CustomTag className={styles.textimage__title}>{section?.header}</CustomTag>

on CustomTag markup in VSCode I get the following error

Type '{ children: string; className: string; }' is not assignable to type 'IntrinsicAttributes'.
  Property 'children' does not exist on type 'IntrinsicAttributes'.ts

How do I define in this case for this component properly the types?

CodePudding user response:

Declare CustomTag type as being keyof JSX.IntrinsicElements. It's going to be like the following code snippet.

const CustomTag: keyof JSX.IntrinsicElements = `${section.header_type}`;
<CustomTag className={styles.textimage__title}>{section?.header}</CustomTag>

Just note that the ${section.header_type} should be a valid HTML tag.

  • Related