Home > Blockchain >  Dynamic prop value in react?
Dynamic prop value in react?

Time:01-13

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).

CodePudding user response:

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]]} />

CodePudding user response:

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']} />

CodePudding user response:

To accomplish the above task you need to create an object with fruits as keys and props as values

const AppleProps = {Name : "Green }
const Fruits = {"Apples", "Banana"}
const FruitsAndProps = {
 Apples: AppleProps
}

CodePudding user response:

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

CodePudding user response:

You need to consider passing your dynamic string inside backticks => `` instead of quotes and use eval() method to convert your string to variable (so that IDE knows you are refering to a variable not a string). The result should look like this:

const ApplesProp = { Name: "Green", Age: 34 }
const Fruits = ["Apples", "Pears", "Oranges"]
console.log(eval(`${Fruits[0]}Prop`))
//the console returns an object. so passing it through props should be fine.
<App prop={eval(`${Fruits[0]}Prop`)}/>

Although there are cleaner ways to solve this, since i don't want to mess with your logic i come up with the above code.

  •  Tags:  
  • Related