uber
uber

Reputation: 5083

How to get a value (not create a string) dynamically?

I am trying to display a value on React like this:

'If THING exists, then show THING'

So far I have

values.price ? `You'll pay ${values.price}` : null

What I need is get

values.price0 ? `You'll pay ${values.price0}` : null
values.price1 ? `You'll pay ${values.price1}` : null
values.price2 ? `You'll pay ${values.price2}` : null
values.price3 ? `You'll pay ${values.price3}` : null

That number will come from the props, so I am trying to do the following, but it doesn't work. How to go about fixing this?

values.price + props.id ? `You'll pay ${values.price + props.id}` : null

Upvotes: 0

Views: 31

Answers (1)

ilkerkaran
ilkerkaran

Reputation: 4344

you can access properties as below ;

values[`${price}${props.id}`] ? `You'll pay ${values.price + props.id}` : null

or you can simply loop through keys

Object.keys(values).map(k => `You'll pay ${values[k]}`)

Upvotes: 3

Related Questions