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

Time:03-16

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.

CodePudding user response:

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} />);

CodePudding user response:

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;
}
  • Related