Home > Back-end >  mapping three different types of component stored in one major state array?
mapping three different types of component stored in one major state array?

Time:07-20

I have the following code inside of my redux state module : this code is for an object the has an array that will have 3 different components inside :

export interface TypeA {
  id: string; 
  type : 'a'
  valueX : 'x'
}
export interface TypeB {
  id: string; 
  type : 'b'
  valueY : 'y'
}
export interface TypeC {
  id: string; 
  type : 'c'
  valueZ : 'z'
}

export interface MajorArr {
  types: {
    [key: string]: (TypeA | TypeB | TypeC)[];
  };
}

below is my mapping faction where I access this array and I want to map those 3 different components depending on the type of the item at current map iteration. the current issue is el on map is giving the 3 items array but cannot know which one is being mapped, the props are different each time.

const typesItems = types[id].map((el) => {
        return (
          <TypeA id={el.id} valueY={el.valueY} />
          <TypeB id={el.id} valueX={el.valueX} />
          <TypeC id={el.id} valueZ={el.valueZ} />
        );
      }
    });

CodePudding user response:

You could use a switch-case to check the type, and thus, render the right component and give the right props.

Something like

const typesItems = types[id].map((el) => {
        switch(el.type) {
          case 'a':
            return <TypeA id={el.id} valueX={el.valueX} />
          case 'b':
            return <TypeB id={el.id} valueY={el.valueY} />
          case 'c':
            return <TypeC id={el.id} valueZ={el.valueZ} />

          default: // Optionally handle unknown type
            return <></>;
      }
});
  • Related