Search code examples
javascriptreactjsdynamicconcatenationjsx

How to concatenate dynamic values in React (JSX)


With my endpoint I can fetch data and set currency as a parameter, so that data received is converted into the currency user chooses. I am passing the currency as a prop into a component that renders that data The problem is that I am having trouble displaying the price dynamically. I am not sure how can I concatenate the JSX correctly... {crypto.quote.${currency}.price.toFixed(2)} just prints the string. Hardcoding the currency (USD, EUR etc) renders the price, but I want it to be dynamic. Thank you, help please :)

import React from 'react';
import { Link } from "react-router-dom"

const Crypto = ({ crypto, currency }) => {

    return <>
        <tr>
            <td>{crypto.cmc_rank}</td>
            <td>
                <Link to={{
                    pathname: `/crypto/${crypto.id}`,
                    state: crypto
                }}>
                    {crypto.name}
                </Link>
            </td>
            <td>{crypto.symbol}</td>
            <td>
                {`crypto.quote.${currency}.price.toFixed(2)`}

            </td>
            <td>{crypto.quote.USD.percent_change_24h}</td>
            <td>
                {crypto.quote.USD.market_cap.toString().slice(0, 3) + "B"}
            </td>
        </tr>

    </>
}

export default Crypto;

Solution

  • Instead of Template Literals which is the reason why you have a string printed out there, you can simply evaluate the values. See below my suggested solution as:

    <td>
        {crypto.quote[currency].price.toFixed(2)}
    </td>
    

    Check below a working example:

    const crypto = { quote: { USD: { price: 120.1122 } } }
    const currency = 'USD'
    
    const result = crypto.quote[currency].price.toFixed(2)
    
    console.log(result)