Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render components dynamically with react and typescript

I have a set of components to render for a multi step form. I'm trying to create a array with all the components then use a map() to include the components.

const stepComponents = [
  <SelectCoach/>,
  <SelectDate/>,
];


<Steps>
  {stepComponents.map((component) => {
     return <component/>
  })}
</Steps>

But I get an type error,

Property 'component' does not exist on type 'JSX.IntrinsicElements'.

Any idea how to fix this?

Thanks you

like image 515
Malinda weerasinghe Avatar asked Oct 31 '25 20:10

Malinda weerasinghe


2 Answers

You can simply use ElementType for the data type and use the name of the components instead of using tags:


import { ElementType } from 'react';

const stepComponents: ElementType[] = [
  SelectCoach,
  SelectDate,
];


<Steps>
  {stepComponents.map((component) => {
     return <component/>
  })}
</Steps>

It is explained here: Dynamic Tag Name Props in React (with TypeScript)

like image 87
Akram Rabie Avatar answered Nov 02 '25 10:11

Akram Rabie


Use below code it should work. In you code you are returning in jsx format, but already in your array it's in the jsx format so no need to convert it into jsx syntax again.

<Steps>
  {stepComponents.map((component) => {
     return component
  })}
</Steps>
like image 20
Bahubali Ak Avatar answered Nov 02 '25 11:11

Bahubali Ak