import React, { useEffect, useState } from "react"; import { BarChart, Bar, XAxis,…
- User
import React, { useEffect, useState } from "react"; import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, LabelList } from "recharts";
interface ProfitAndLossType { day: string loss: string profit: string }
interface ProfitAndLossByDaysProps { data: ProfitAndLossType[]; }
export default function ProfitAndLossByDays({data}: ProfitAndLossByDaysProps) { const [myData, setmyData] = useState<ProfitAndLossType[]>([])
// useEffect(() => {
const dataWithPercentages = data.map((item) => { const parseProfit = parseFloat(`${item.profit}`).toFixed(2) const parseLoss = parseFloat(`${item.loss}`).toFixed(2) const total = Math.abs(+parseLoss) + Math.abs(+parseProfit); return { ...item, lossPercent: +((Math.abs(+parseLoss) / total) * 100).toFixed(2), profitPercent: +((Math.abs(+parseProfit) / total) * 100).toFixed(2), percent: 100, } })// setmyData(updatedData) // }, [data])
return ( <BarChart width={500} // height={300} data={dataWithPercentages} margin={{ top: 20, right: 30, left: 20, bottom: 5 }} > <Bar dataKey="profitPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#89ADA0" > <Bar dataKey="lossPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#ECECEC"> ); }
- Добавь код добавления процентов в useState и в useEffect и сетай в useState myData, data не должен изменяться..
- сделай кастомный LabelList , чтобы dataKey был profitPercent, а значение, которое он должен отображать profit, так же и с <LabelList dataKey="lossPercent", dataKey lossPercent, а отображать на экране значение, данные он должен loss
- Assistant
Here is the updated code:
- User
'CustomLabelList' cannot be used as a JSX component. Its return type 'Element[]' is not a valid JSX element. Type 'Element[]' is missing the following properties from type 'Element': type, props, keyts(2786)
value={item[valueKey.replace("Percent", "")]}Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProfitAndLossType'. No index signature with a parameter of type 'string' was found on type 'ProfitAndLossType'.ts(7053)
Используй typescript, добавь везде typescript и исправь ошибки, работает некорректно
- Assistant
- User
Ошибок нету, но CustomLabelList не отображается https://recharts.org/en-US/examples/BarChartWithMinHeight Посмотри что может быть не так, почему не отображается label вообще?
- Assistant
- User
const data = [ { name: "Page A", uv: 4000, profit: 2400, }, { name: "Page B", uv: 3000, profit: 1398, }, { name: "Page C", uv: 2000, profit: 9800, } ];
посчитать общую сумму profit reduce
- Assistant
You can use the
reducemethod to calculate the total profit from thedataarray:const totalProfit = data.reduce((accumulator, currentValue) => { return accumulator + currentValue.profit; }, 0); console.log(totalProfit); // Output: 13798In the code above,
accumulatoris initialized with0, and for each item in thedataarray, theprofitvalue is added to theaccumulator. After iterating through all the items, thetotalProfitwill be equal to the sum of all profit values.