I am struggling with converting this piece of code to typescript, as I am a newbie with TS.
import React from 'react';
import './Coin.css';
type Coin = {
name : string;
price : string;
symbol: string;
marketcap: string;
volume: string;
image: string;
priceChange: string;
}
{
return (
<div className='coin-container'>
<div className='coin-row'>
<div className='coin'>
<img src={image} alt='crypto' />
<h1>{name}</h1>
<p className='coin-symbol'>{symbol}</p>
</div>
<div className='coin-data'>
<p className='coin-price'>€{price}</p>
<p className='coin-volume'>€{volume.toLocaleString()}</p>
{priceChange < 0 ? (
<p className='coin-percent red'>{priceChange.toFixed(2)}%</p>
) : (
<p className='coin-percent green'>{priceChange.toFixed(2)}%</p>
)}
<p className='coin-marketcap'>
Mkt Cap: ${marketcap.toLocaleString()}
</p>
</div>
</div>
</div>
);
};
export default Coin;
I know I have to change this piece of code:
const Coin = ({
name,
price,
symbol,
marketcap,
volume,
image,
priceChange
}) => {
return (
because VSCode gives me errors, but I am not sure how to declare it and after pass it to the return function. I have tried this:
type Coin = { name : string; price : string; symbol: string; marketcap: string; volume: string; image: string; priceChange: string; }
and it gives me error that A 'return' statement can only be used within a function body.
You should first declare your types in an interface or a type (it's better to be an interface, because interfaces are straight forward and can be extended when you need to extend a type.
Then declare a const with the type Functional Component (here is React.FC) with passing the props type as generic (types inside <> are called generic).
Now you can use the inputs without need of declaring types anymore. (make sure your file type is .tsx, because .tsx files are Typescript files with React JSX support.
interface CoinProps {
name: string;
price: string;
symbol: string;
marketcap: string;
volume: string;
image: string;
priceChange: string;
}
const Coin: React.FC<CoinProps> = ({
image,marketcap,name,price,priceChange,symbol,volume
}) => {
return (
<div className="coin-container">
<div className="coin-row">
<div className="coin">
<img src={image} alt="crypto" />
<h1>{name}</h1>
<p className="coin-symbol">{symbol}</p>
</div>
<div className="coin-data">
<p className="coin-price">€{price}</p>
<p className="coin-volume">€{volume.toLocaleString()}</p>
{priceChange < 0 ? (
<p className="coin-percent red">{priceChange.toFixed(2)}%</p>
) : (
<p className="coin-percent green">{priceChange.toFixed(2)}%</p>
)}
<p className="coin-marketcap">
Mkt Cap: ${marketcap.toLocaleString()}
</p>
</div>
</div>
</div>
);
};
export default Coin;
By the way, the price change should be a number.