Ian
Ian

Reputation: 193

Tyepscript Array.map returns array of JSX.Element instead of custom component type

var items = values.map((x, index) =>
   <CustomComponent key={index} />);

This returns JSX.Element[]. Why doesn't it return typeof CustomComponent[]?

With the former, then I can't use items.sort without difficult errors.

Upvotes: 0

Views: 623

Answers (2)

levent
levent

Reputation: 3634

yes,

like Egor said, your map result is CustomComponent resuls array.

if you want to your component instance array try some thing like this

export  type CustomComponentType = () => JSX.Element;

export  const CustomComponent : CustomComponentType = ()=> {
    return <div>my componen result</div>
} 

export const test : CustomComponentType[] = ()=> {
    const array = [1,2,3,4,5,6,7,8,9];
    const componentArray =  array.map(c => CustomComponent);
    return componentArray;
}

Upvotes: 0

Egor Pashko
Egor Pashko

Reputation: 354

It's correct. It returns JSX.Element[] because you are rendering CustomComponent immediately. If you want to work with element sort/filter or something else you need filter data before render.

values
   .filter(x => //filter your values)
   .map((x, index) => // render your components
<CustomComponent key={index} />);

Upvotes: 2

Related Questions