This is component in react use tailwind CSS
import React, { useEffect, useState } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
const CryptoPrices = () => {
const [cryptoData, setCryptoData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchCryptoData = async () => {
try {
setLoading(true);
const response = await axios.get(
"https://api.coingecko.com/api/v3/coins/markets",
{
params: {
vs_currency: "usd",
order: "market_cap_desc",
per_page: 60,
page: 1,
sparkline: true,
price_change_percentage: "1h,24h",
},
}
);
setCryptoData(response.data);
} catch (error) {
setError("Failed to fetch cryptocurrency data.");
} finally {
setLoading(false);
}
};
fetchCryptoData();
}, []);
const formatNumber = (num) => {
if (num >= 1e12) {
return `$ ${(num / 1e12).toFixed(2)}T`;
} else if (num >= 1e9) {
return `$ ${(num / 1e9).toFixed(2)}B`;
} else if (num >= 1e6) {
return `$ ${(num / 1e6).toFixed(2)}M`;
} else {
return `$ ${num.toLocaleString()}`;
}
};
const renderSparkline = (data) => {
const width = 100;
const height = 30;
const max = Math.max(...data);
const min = Math.min(...data);
const points = data.map((d, i) => {
const x = (i / (data.length - 1)) * width;
const y = ((d - min) / (max - min)) * height;
return [x, height - y];
});
const pathD = points
.map((point, index) => {
const [x, y] = point;
return `${index === 0 ? "M" : "L"}${x},${y}`;
})
.join(" ");
// Determine the color based on the price change
const color = data[0] < data[data.length - 1] ? "green" : "red";
return (
);
};
return (
<>
Today's Cryptocurrency Prices by Market Cap
{/* table of crypto */}
{loading ? (
Loading...
) : error ? (
{error}
) : (
# Rank
Name
Price
1h
24h
Volume (24h)
Market Cap
Chart
{cryptoData.map((crypto) => (
{crypto.market_cap_rank}
{crypto.name}
{crypto.symbol}
${crypto.current_price.toLocaleString()}
= 0
? "text-green-500"
: "text-red-500"
}`}
>
{crypto.price_change_percentage_1h_in_currency.toFixed(
2
)}
%
= 0
? "text-green-500"
: "text-red-500"
}`}
>
{crypto.price_change_percentage_24h.toFixed(2)}%
{formatNumber(crypto.total_volume)}
{formatNumber(crypto.market_cap)}
{renderSparkline(crypto.sparkline_in_7d.price)}
))}
)}
>
);
};
export default CryptoPrices;
Post a Comment