1

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?

4
  • What type is section.header_type? Commented Sep 1, 2022 at 20:49
  • section.header_type is an enum for headers like h1, h2, h2 and is definable in backend. Commented Sep 1, 2022 at 20:52
  • Does this answer your question? stackoverflow.com/questions/40960411 Commented Sep 1, 2022 at 21:12
  • Hi @lepsch the code alone works, just the type is not correct Commented Sep 1, 2022 at 21:52

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for Feedback this approach hints the following Type 'string' is not assignable to type 'keyof IntrinsicElements'.ts(2322)
Try this instead: const CustomTag = `${section.header_type}` as keyof JSX.IntrinsicElements;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.