Malinda weerasinghe
Malinda weerasinghe

Reputation: 107

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

Upvotes: 4

Views: 5925

Answers (5)

Akram Rabie
Akram Rabie

Reputation: 545

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)

Upvotes: 3

Veljko Blagojevic
Veljko Blagojevic

Reputation: 427

You should just return component, without using <>.

Working example here: https://codesandbox.io/s/hopeful-varahamihira-35etf1?file=/src/App.tsx

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

But if you don't need to map over them, then I would suggest not using map at all and just use:

<Steps>
  {stepComponents}
</Steps>

Upvotes: 0

Karthikeyan
Karthikeyan

Reputation: 414

I think the problem is in your array

const stepComponents = [
  SelectCoach,
  SelectDate,
];


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

Upvotes: 0

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4754

You've already instantiated the components in your stepComponents array, and you don't need to do so again when rendering them through the map:

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

or more simply

<Steps>
  {stepComponents}
</Steps>

Upvotes: 0

Bahubali Ak
Bahubali Ak

Reputation: 246

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>

Upvotes: 1

Related Questions