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:
import React, { useEffect, useState } from "react"; import { BarChart, Bar, XAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, Label, } from "recharts"; interface ProfitAndLossType { day: string; loss: string; profit: string; } interface ProfitAndLossByDaysProps { data: ProfitAndLossType[]; } const CustomLabelList = ({ data, valueKey, color, fontSize }) => { return data.map((item, index) => ( <Label key={index} x={index * 60} y={valueKey === "lossPercent" ? 110 : 80} fill={color} fontSize={fontSize} value={item[valueKey.replace("Percent", "")]} /> )); }; 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(dataWithPercentages); }, [data]); return ( <ResponsiveContainer width="100%" height={260}> <BarChart width={500} data={myData} margin={{ top: 20, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="day" /> <Tooltip /> <Bar dataKey="profitPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#89ADA0" > <CustomLabelList data={myData} valueKey="profitPercent" color="#B0B0B0" fontSize={13} /> </Bar> <Bar dataKey="lossPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#ECECEC" > <CustomLabelList data={myData} valueKey="lossPercent" color="#fff" fontSize={13} /> </Bar> </BarChart> </ResponsiveContainer> ); }I added a CustomLabelList component to display the correct values for profit and loss labels.
- 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
Here's the revised code with proper TypeScript types and no errors:
import React, { useEffect, useState } from "react"; import { BarChart, Bar, XAxis, CartesianGrid, Tooltip, ResponsiveContainer, Label, } from "recharts"; interface ProfitAndLossType { day: string; loss: string; profit: string; } interface ProfitAndLossByDaysProps { data: ProfitAndLossType[]; } interface CustomLabelListProps { data: ProfitAndLossType[]; valueKey: "profitPercent" | "lossPercent"; color: string; fontSize: number; } const CustomLabelList: React.FC<CustomLabelListProps> = ({ data, valueKey, color, fontSize, }) => { return ( <> {data.map((item, index) => { const value = valueKey === "profitPercent" ? item.profit : item.loss; return ( <Label key={index} x={index * 60} y={valueKey === "lossPercent" ? 110 : 80} fill={color} fontSize={fontSize} value={value} /> ); })} </> ); }; 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(dataWithPercentages); }, [data]); return ( <ResponsiveContainer width="100%" height={260}> <BarChart width={500} data={myData} margin={{ top: 20, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="day" /> <Tooltip /> <Bar dataKey="profitPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#89ADA0" > <CustomLabelList data={myData} valueKey="profitPercent" color="#B0B0B0" fontSize={13} /> </Bar> <Bar dataKey="lossPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#ECECEC" > <CustomLabelList data={myData} valueKey="lossPercent" color="#fff" fontSize={13} /> </Bar> </BarChart> </ResponsiveContainer> ); }I've added TypeScript types for the
CustomLabelListcomponent and updated the return type to use a fragment<>instead of mapping directly to an array of elements. This should resolve the TypeScript errors. - User
Ошибок нету, но CustomLabelList не отображается https://recharts.org/en-US/examples/BarChartWithMinHeight Посмотри что может быть не так, почему не отображается label вообще?
- Assistant
I apologize for the confusion earlier. Instead of using a separate
<Label>component, we can use the<LabelList>component with a customcontentprop to achieve the desired result.Here's the updated code:
import React, { useEffect, useState } from "react"; import { BarChart, Bar, XAxis, CartesianGrid, Tooltip, 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(dataWithPercentages); }, [data]); const CustomLabel = (props) => { const { x, y, value, textAnchor, index, dataKey } = props; const dataValue = dataKey === "profitPercent" ? data[index].profit : data[index].loss; return ( <text x={x} y={y} dy={-4} textAnchor={textAnchor} fontSize="13" fill="#fff"> {dataValue} </text> ); }; return ( <ResponsiveContainer width="100%" height={260}> <BarChart width={500} data={myData} margin={{ top: 20, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="day" /> <Tooltip /> <Bar dataKey="profitPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#89ADA0" > <LabelList dataKey="profitPercent" content={CustomLabel} fill="#B0B0B0" fontSize={13} /> </Bar> <Bar dataKey="lossPercent" radius={[9, 9, 9, 9]} barSize={60} stackId="a" fill="#ECECEC" > <LabelList dataKey="lossPercent" content={CustomLabel} fill="#fff" fontSize={13} /> </Bar> </BarChart> </ResponsiveContainer> ); }In this updated code, I have removed the
CustomLabelListcomponent and instead added aCustomLabelfunction which returns a<text>element. I've also used the<LabelList>component with thecontentprop set toCustomLabelfor both bars.Now, the custom labels should be properly displayed on the chart.
- 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.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.