I'm currently working on a React App, and I have a component for a tabular data. I am calling an API endpoint that gives a response like this:
{
"bitcoin": {
"usd": 48904,
"usd_market_cap": 925245685071.0829,
"usd_24h_vol": 21781197864.07206,
"usd_24h_change": -0.4811309022054875,
"last_updated_at": 1640267722
}
}
The way I structured my components are it accepts "bitcoin" as one of the arguments for the API endpoint, and rendering the data in my child component is like this:
<TableCell>{data.bitcoin.usd_market_cap}</TableCell>
<TableCell>{data.bitcoin.usd_24h_vol}</TableCell>
<TableCell>{data.bitcoin.usd_24h_change}</TableCell>
How can I change the bitcoin part in my rendering code so that it can accept the prop that I added to the component like this:
<CoinTableRow coin="bitcoin" currency="usd" />
so that I can just use do:
<CoinTableRow coin="ethereum" currency="usd" />
CodePudding user response:
Any object can have its properties accessed in one of two ways: either by using the dot syntax you're using now, e.g. data.bitcoin
, or by using array access syntax, e.g. data["bitcoin"]
.
So simply replace all instances of data.bitcoin
with data[props.coin]
:
<TableCell>{data[props.coin].usd_market_cap}</TableCell>
<TableCell>{data[props.coin].usd_24h_vol}</TableCell>
<TableCell>{data[props.coin].usd_24h_change}</TableCell>