简体   繁体   中英

React Typescript on dynamic component

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM