I want a dynamic prop value for react. I already have a list of Fruits, but my prop value should be Fruits[0] + 'prop'
For example: ApplesProp
index.js
const ApplesProp = { Name: "Green", Age: 34 }
const Fruits = ["Apples", "Pears", "Oranges"]
<App prop={dynamic-fruit+'Prop'} />
Tried
<App prop={Fruits[0]+'Prop'}/>
but this results in passing the string: 'ApplesProp' not the ApplesProp object (i.e. Name: Green, Age: 34).
Fruits[0]+'Prop'
Adding a string to a string returns a string.
To accomplish what you need, you can create an object with fruits as keys and props as values:
const fruitVsProps = {
Apples: ApplesProp
// add more as you like
}
<App prop={fruitVsProps[Fruits[0]]} />
there is two way you can Do it. 1.better way use array.map() then pass to your props.
let Fruits = ["Apples", "Pears", "Oranges"];
<ff> {Fruits.map((item)=>{<App props={item} /> })} </ff>
2.second way you can use literal template
Create an object and add your object in that
const props = {
ApplesProp: { Name: "Green", Age: 34 }
}
const Fruits = ["Apples", "Pears", "Oranges"]
console.log(props[Fruits[0]+'Prop'])
and now you could use it like
<App prop={props[Fruits[0]+'Prop']} />