Home > Enterprise >  react pass object key as prop
react pass object key as prop

Time:05-09

I want to pass array of strings from parent function component to child function component. At the child component the array should reflect the object key.

For example, send the following array from a parent BY PROP: let colors = ['red','green','white']

and at the child component I have the following variable:

let arr = [config.red, config.green, config.white, config.blue]; 

I want to take the ".red, .green, .white" from the props and then go over the config variable below:

const config: {
red: {
    base: string;
    icon: any;
    name: string;
    target: string;
};
white: {
    base: number;
    icon: any;
    name: string;
    target: string;

...

Be very glad for any help. Best.

CodePudding user response:

<Child colors={["red", "green", "white"]} />

and inside Child, you can get the respective config object, using map and iterating over it

const arr = props.colors.map((item,index)=>{
      
       return config[item];
})

CodePudding user response:

Pass the array of keys to your component...

<Child colors={colors} />

then reduce that array to the matching keys from config

const arr = props.colors.reduce(
  (acc, key) => (key in config ? [...acc, config[key]] : acc),
  []
);

I'm using reduce() instead of a simple map() in order to filter out keys that might not be in config.

  • Related