shadcn-ui / ui

Beautifully designed components that you can copy and paste into your apps. Accessible. Customizable. Open Source.
https://ui.shadcn.com
MIT License
74k stars 4.56k forks source link

[bug]: chart not rendering #4231

Open ronijaat opened 4 months ago

ronijaat commented 4 months ago

Describe the bug

Hey, I am using charts, and everything was working fine, but now suddenly the pie chart is not rendering. This happens when I use two pie charts side by side. but it rendered the data. see the below image

charts-bug

Affected component/components

chart

How to reproduce

no

Codesandbox/StackBlitz link

No response

Logs

No response

System Info

node-20
next-14

Before submitting

oleksii-sploro commented 4 months ago

can you please send the code?

jxryft commented 4 months ago

Check to make sure the ChartContainer component has a minimum height class or style attribute e.g: min-h-[300px]. The issue that I had was that I was using the tailwindcss aspect plugin. Removing this allowed my charts to render properly.

borgogelli commented 3 months ago

Same problem for me. No examples from shadcn-ui's docs works with next-js 15 and react 19. But if I use a recharts' official example, it works.

muhammetakalan commented 3 months ago

You might be experiencing this issue because Recharts is not yet compatible with React 19. If you have upgraded to React 19, you may need to wait for Recharts to update or revert to a compatible version to resolve the issue.

https://github.com/shadcn-ui/ui/issues/4231

borgogelli commented 3 months ago

You might be experiencing this issue because Recharts is not yet compatible with React 19. If you have upgraded to React 19, you may need to wait for Recharts to update or revert to a compatible version to resolve the issue.

4231

Rechart 2.13.0-alpha.4 with React 19.0.0-beta works fine with NextJs 15. Only shadcn's chart examples doesn't work.

dludemann commented 3 months ago

react-is is breaking in recharts 2.13.0-alpha.4 & react 19 / next 15.

You need to manually override this in your package.json

"dependencies": {
    "react-is": "19.0.0-rc-6f23540c7d-20240528"
},
"overrides": {
    "recharts": {
        "react-is": "$react-is"
    }
}

See below thread over at recharts. https://github.com/recharts/recharts/issues/4558#issuecomment-2135604065

Updating the above has shadcn charts working on my next 15 / react 19 project with recharts alpha.

May need to update below screenshot in the docs.

Screenshot 2024-07-13 at 1 45 44 AM
AlexSchwabauer commented 3 months ago

The charts are not visible for me as well.

Only when explicitly setting width and height props for the recharts Chart Component (e.g. BarChart or LineChart), the chart is visible. However, responsiveness is lost due to this. Seems like the ChartContainer wrapper around ResponsiveContainer does not work?

Any suggestions?

ryanburns23 commented 3 months ago

Check to make sure the ChartContainer component has a minimum height class or style attribute e.g: min-h-[300px]. The issue that I had was that I was using the tailwindcss aspect plugin. Removing this allowed my charts to render properly.

If you are using the @tailwindcss/aspect-ratio plugin, you can follow the instructions on the "Compatibility with default aspect-ratio utilities" section of the readme to support the default aspect-ratio utilities these charts rely on.

dludemann commented 3 months ago

The charts are not visible for me as well.

Only when explicitly setting width and height props for the recharts Chart Component (e.g. BarChart or LineChart), the chart is visible. However, responsiveness is lost due to this. Seems like the ChartContainer wrapper around ResponsiveContainer does not work?

Any suggestions?

See my above suggestion if you are using React 19 or Next 15 https://github.com/shadcn-ui/ui/issues/4231#issuecomment-2226782779

By forcing the rc version of react-is (which supports react 19 rc / 15 rc) the shadcn examples work out of the box and the ChartContainer is responsive for me using the min-h that shadcn tells you to.

react-is is a dependency for recharts that hasn't been updated yet in the recharts package. Hence, why you need to force the update.

emkooz commented 3 months ago

Running into the same issue here with React 19 + Next 15. Tried all of the suggestions posted so far and still cannot get a responsive chart to render.

Examples taken directly from the recharts docs render normally when explicitly setting width and height, however the ResponsiveContainer examples do not render.

Was able to reproduce on a new create-next-app project while trying all of the fixes above, tested on Firefox 128 and Chromium 125.0.6422.141.

AlexandreLrz commented 3 months ago

Same for me here with Next JS 14, React 18. I will investigate more during the day EDIT : I modified the ChartContainer component by removing the wrapper div and this solved the issue for me.

thanhlq commented 3 months ago

I got the same issue, charts are not visible (in shadcn examples) with Nextjs 15-rc and React 19-rc! (just a try) Working fine with Nextjs 14 and React 18

To reproduce: simple replace shadcn/apps/www/package.json with next: 15.0.0-rc.0 and react: rc and react-dom: rc

ronijaat commented 3 months ago

The main issue is that charts don't render correctly with dynamic data.

"First bug I found on GitHub."🫡

SsyraxX commented 3 months ago

Goodmorging at least for me,

I encountered the same issue where the Shadcn chart would not render, and I managed to solve it after through investigation. The primary problem seemed to be that wrapping a div, card, or any other element outside the ChartContainer prevents the chart from rendering. I tried the suggestion by AlexandreLrz to remove the wrapper div, which worked temporarily but wasn't an ideal solution for my needs.

To get to the bottom of this, I created a new Next.js 14 app and meticulously set it up by installing charts, shadcn, Tailwind CSS, and other necessary dependencies. Upon rendering a chart, it worked perfectly fine!

I didn't stop there. I conducted a comprehensive comparison of the package.json, tailwind.config.js, and other configuration files between my new working setup and the problematic one. I examined dependencies, configurations, and potential conflicts thoroughly.

After extensive debugging, I discovered that removing require("@tailwindcss/aspect-ratio") from the plugins section in tailwind.config.js resolved the rendering issue. Once this line was removed, the charts rendered flawlessly without any further problems. To double-check, I added the aspect-ratio plugin to the new app, which caused the chart to stop rendering. This confirmed that the plugin was the culprit, interfering with the ChartContainer in some way.

I hope i save some debug time for you guys to day!

RakeshPotnuru commented 3 months ago

Removing the wrapper div worked for me (React 18, Next.js 14). I guess the chart needs to be a separate component.

MoDev2002 commented 2 months ago

the issue for me was that the shadcn example used max-h-[250px] in the ChartContainer component, while the documentation states to use min-h-[your-height]. So, after replacing max with min everything worked correctly.

vbylen commented 2 months ago

for people using yarn this is what worked for me:

  "resolutions": {
    "react-is": "^19.0.0-rc-2d2cc042-20240809"
  },
victorbr988 commented 2 months ago

My chart not render with dynamic data, I am using React 18 and this is my code:

export function PieChartCustom({ chartData = [], datakey, namekey }) {
  return (
    <ChartContainer
      config={chartConfig}
      className="min-h-[250px]"
    >
      <PieChart>
        <ChartTooltip
          cursor={false}
          content={<ChartTooltipContent hideLabel />}
        />
        <Pie data={chartData} dataKey={datakey} nameKey={namekey} />
      </PieChart>
    </ChartContainer>
  )
}
mohamedamara1 commented 2 months ago

I'm using a LineChart and the line is not rendering, Nextjs 14 and React 18

ctff-kongchang commented 2 months ago

Goodmorging at least for me,

I encountered the same issue where the Shadcn chart would not render, and I managed to solve it after through investigation. The primary problem seemed to be that wrapping a div, card, or any other element outside the ChartContainer prevents the chart from rendering. I tried the suggestion by AlexandreLrz to remove the wrapper div, which worked temporarily but wasn't an ideal solution for my needs.

To get to the bottom of this, I created a new Next.js 14 app and meticulously set it up by installing charts, shadcn, Tailwind CSS, and other necessary dependencies. Upon rendering a chart, it worked perfectly fine!

I didn't stop there. I conducted a comprehensive comparison of the package.json, tailwind.config.js, and other configuration files between my new working setup and the problematic one. I examined dependencies, configurations, and potential conflicts thoroughly.

After extensive debugging, I discovered that removing require("@tailwindcss/aspect-ratio") from the plugins section in tailwind.config.js resolved the rendering issue. Once this line was removed, the charts rendered flawlessly without any further problems. To double-check, I added the aspect-ratio plugin to the new app, which caused the chart to stop rendering. This confirmed that the plugin was the culprit, interfering with the ChartContainer in some way.

I hope i save some debug time for you guys to day!

This is exactly what I did and Charts started working again, remove that plugin and uninstall that!

victorbr988 commented 2 months ago

My chart not render with dynamic data, I am using React 18 and this is my code:

export function PieChartCustom({ chartData = [], datakey, namekey }) {
  return (
    <ChartContainer
      config={chartConfig}
      className="min-h-[250px]"
    >
      <PieChart>
        <ChartTooltip
          cursor={false}
          content={<ChartTooltipContent hideLabel />}
        />
        <Pie data={chartData} dataKey={datakey} nameKey={namekey} />
      </PieChart>
    </ChartContainer>
  )
}

I solved my problem, it turns out that in my data structure, the nameKey value was a string and not a number

caiolv commented 1 month ago

I manage to fix it by forcing two things:

It's working even with dynamic data!

Example:

import { convertCategoriesToChartConfigAndData } from '@/app/lib/chart-utils';
import { Cell, Pie, PieChart, ResponsiveContainer } from 'recharts';

export function ChartTestComponent() {
  const dataTest = [
    {
      name: 'rent',
      value: 150.00, //previously was value: '150.00',
      fill: '#f9a653',
    },
    {
      name: 'entertainment',
      value: 189.20, //previously was value: '189.20',
      fill: '#4BC0C0',
    },
  ];

  return (
    <ResponsiveContainer>
      <PieChart width={800} height={400}>
        <Pie
          data={dataTest}
          cx={120}
          cy={200}
          innerRadius={60}
          outerRadius={80}
          paddingAngle={5}
          dataKey='value'
        >
          {dataTest.map((category, index) => (
            <Cell key={`cell-${index}`} fill={category.fill} />
          ))}
        </Pie>
      </PieChart>
    </ResponsiveContainer>
  );
}
carlos-mta commented 4 weeks ago

I solved it using this CSS code in my global stylesheet file:

.recharts-responsive-container {
    height: initial !important;
}

Component code:

export function SimpleBarChart() {
    return (
        <Card>
            <CardHeader>
                <CardTitle>Bar Chart</CardTitle>
                <CardDescription>January - June 2024</CardDescription>
            </CardHeader>
            <CardContent>
                <ChartContainer className="min-h-[300px]" config={chartConfig}>
                    <BarChart accessibilityLayer data={chartData}>
                        <CartesianGrid vertical={false} />
                        <XAxis
                            dataKey="month"
                            tickLine={false}
                            tickMargin={10}
                            axisLine={false}
                            tickFormatter={(value) => value.slice(0, 3)}
                        />
                        <ChartTooltip
                            cursor={false}
                            content={<ChartTooltipContent hideLabel />}
                        />
                        <Bar
                            dataKey="desktop"
                            fill="var(--color-desktop)"
                            radius={8}
                        />
                    </BarChart>
                </ChartContainer>
            </CardContent>
            <CardFooter className="flex-col items-start gap-2 text-sm">
                <div className="flex gap-2 font-medium leading-none">
                    Trending up by 5.2% this month{' '}
                    <TrendingUp className="h-4 w-4" />
                </div>
                <div className="leading-none text-muted-foreground">
                    Showing total visitors for the last 6 months
                </div>
            </CardFooter>
        </Card>
    )
}
logemann commented 3 weeks ago

for people using yarn this is what worked for me:

  "resolutions": {
    "react-is": "^19.0.0-rc-2d2cc042-20240809"
  },

This is the thing which is the main problem with React 19 RC and NextJS 15 RC. Otherwise you wont see any SVG in your code. So definitely not a HTML/CSS issue.

ruimarcosjoao commented 2 weeks ago

I manage to fix it by forcing value to be a Number instead of String and adding width and height to PieChart component. It's working even with dynamic data!

For example, in this component

import { convertCategoriesToChartConfigAndData } from '@/app/lib/chart-utils';
import { Cell, Pie, PieChart, ResponsiveContainer } from 'recharts';

export function ChartTestComponent() {
  const dataTest = [
    {
      name: 'rent',
      value: '150.00',
      fill: '#f9a653',
    },
    {
      name: 'entertainment',
      value: '189.20',
      fill: '#4BC0C0',
    },
    {
      name: 'random',
      value: '5.55',
      fill: '#00ff5a',
    },
  ];

  return (
    <ResponsiveContainer>
      <PieChart width={800} height={400}>
        <Pie
          data={dataTest}
          cx={120}
          cy={200}
          innerRadius={60}
          outerRadius={80}
          paddingAngle={5}
          dataKey='value'
        >
          {dataTest.map((category, index) => (
            <Cell key={`cell-${index}`} fill={category.fill} />
          ))}
        </Pie>
      </PieChart>
    </ResponsiveContainer>
  );
}

Change dataTest to

  const dataTest = [
    {
      name: 'rent',
      value: 150.00, //here
      fill: '#f9a653',
    },
    {
      name: 'entertainment',
      value: 189.20, //here
      fill: '#4BC0C0',
    },
    {
      name: 'random',
      value: 5.55, //and here
      fill: '#00ff5a',
    },
  ];

Thanks, this solved my problem

lucarosato1 commented 2 weeks ago

I finally solved it, nothing I searched for worked, but I found a way to solve it by trying. First I'll explain my problem:

I was trying to use literally any chart from the ones in the documentation, but NONE of them showed me the graphic part of the chart, the text, but nothing about the chart. The error was that all the charts in the documentation are without the width and height defined.

It was quite a headache to guess that the BarChart component requires you to pass its dimensions as a parameter (without being required/mandatory by the component itself!!!)

<BarChart width={500} height={250}>

[edit] Oh and I'd like to mention in case you're wondering, yes, I'm on the latest version of React and Next.

arno-fukuda commented 2 weeks ago

@lucarosato1, width and heigh shouldn't be needed for the shadcn components. The BarChart example from their docs renders just fine as is.

lucarosato1 commented 2 weeks ago

@lucarosato1, width and heigh shouldn't be needed for the shadcn components. The BarChart example from their docs renders just fine as is.

Hmm that's weird because I literally copied and pasted it into a new and clean Shadcn and Next project and nothing of the graphic is visible until I manually enter the dimensions (tested in Firefox, Safari and Brave)

arno-fukuda commented 2 weeks ago

Hmm that's weird because I literally copied and pasted it into a new and clean Shadcn and Next project and nothing of the graphic is visible until I manually enter the dimensions (tested in Firefox, Safari and Brave)

A new and clean Next project will be on 15.0.1 with React 19-rc. That's why you still have to override the react-is dependency.

FifthWit commented 2 weeks ago

e

god that is absurd I wasted so much time trying to figure it out only for it to be that :( that sucks, also is there a way to not have to define the width so it takes up full like w-full tailwind?

AsazuTaiga commented 1 week ago

for pnpm users:

{
  "dependencies": {
    "react-is": "19.0.0-rc-6f23540c7d-20240528"
  },
  "pnpm": {
    "overrides": {
      "recharts>react-is": "$react-is"
    }
  }
}
FifthWit commented 1 week ago

so I am trying to make it automatically scale like it would with a responsive container but it doesnt appear if I dont define the width/height I dont understant because in other projects its worked just fine

    <ChartContainer config={chartConfig} className="min-h-[200px] max-h-[400px] w-full">
      <BarChart accessibilityLayer data={chartData} > {/*add width and height to make it appear*/}
        <CartesianGrid vertical={false} />
        <XAxis
          dataKey="day"
          tickLine={false}
          tickMargin={10}
          axisLine={false}
          tickFormatter={(value) => value.slice(0, 3)}
        />
        <ChartTooltip
          cursor={true}
          content={<ChartTooltipContent hideLabel />}
        />
        <Bar dataKey="Submission" fill="var(--color-Submission)" radius={8} />
      </BarChart>
    </ChartContainer>
lucarosato1 commented 1 week ago

so I am trying to make it automatically scale @FifthWit

I'm sharing here a hook I made especially for that, I'm not sure it's the most pro thing out there because I'm just a backend dev who's doing front-end work

Basically what it does is grab the size of your screen, do a resize and return the width as a numeric (which is the only thing that chart components support as dimensions), so just use the useResize hook and grab the width.

Oh and that "-150" is something I needed for my particular view, adjust it as needed.

Custom useResize hook:

import { useState, useEffect } from 'react';

const useResize = () => {
    const [windowSize, setWindowSize] = useState({
        width: window.innerWidth - 150,
        height: window.innerHeight,
    });

    useEffect(() => {
        const handleResize = () => {
            setWindowSize({
                width: window.innerWidth - 150,
                height: window.innerHeight,
            });
        };

        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    return windowSize;
};

export default useResize;

Example using it for a component with a chart:

export function YourEpicComponent() {
    const dimensions = useResize();

    return (
            <ChartContainer config={chartConfig}>
                <AreaChart
                        accessibilityLayer
                        data={getData()}
                        width={dimensions.width} // Use the width
                        height={150}
                    >
                    ...
pankaj-kumar-yadav commented 1 week ago

Can someone help me solve this? using nextjs and react 18.2, whenever i tried copy and paste even shadcn charts example getting this error

image

richardnguyen99 commented 1 week ago

Goodmorging at least for me,

I encountered the same issue where the Shadcn chart would not render, and I managed to solve it after through investigation. The primary problem seemed to be that wrapping a div, card, or any other element outside the ChartContainer prevents the chart from rendering. I tried the suggestion by AlexandreLrz to remove the wrapper div, which worked temporarily but wasn't an ideal solution for my needs.

To get to the bottom of this, I created a new Next.js 14 app and meticulously set it up by installing charts, shadcn, Tailwind CSS, and other necessary dependencies. Upon rendering a chart, it worked perfectly fine!

I didn't stop there. I conducted a comprehensive comparison of the package.json, tailwind.config.js, and other configuration files between my new working setup and the problematic one. I examined dependencies, configurations, and potential conflicts thoroughly.

After extensive debugging, I discovered that removing require("@tailwindcss/aspect-ratio") from the plugins section in tailwind.config.js resolved the rendering issue. Once this line was removed, the charts rendered flawlessly without any further problems. To double-check, I added the aspect-ratio plugin to the new app, which caused the chart to stop rendering. This confirmed that the plugin was the culprit, interfering with the ChartContainer in some way.

I hope i save some debug time for you guys to day!

I can confirm that Tailwind plugin aspect-ratio might cause this problem. My problem was not simply missing some min-height classnames. The rendered HTML in inspection does not show any element inside the chart container. If that is your case, removing the plugin from Tailwind config works.

matheusvictoor commented 1 week ago

Solution for Chart Rendering Issue with Next.js 15 and React 19

I was facing difficulties rendering charts using the Shadcn examples with Next.js 15 and React 19.

I followed the instructions found in the Shadcn documentation. Below are the steps that worked for me:

Steps to resolve:

  1. Update the package.json: I adjusted the versions of React and Next.js to ensure compatibility:

    
    {
     "dependencies": {
       "react": "19.0.0-rc-69d4b800-20241021",
       "react-dom": "19.0.0-rc-69d4b800-20241021",
       "next": "15.0.1"
     }
    }
  2. Force the correct version of react-is: To ensure Recharts works correctly with React 19, I added the following configuration:

    {
    "overrides": {
      "recharts": {
        "react-is": "$react-is"
      }
    }
    }

My package.json

{
  ...
  "scripts": {
    ...
  },
  "dependencies": {
    ...
    "next": "15.0.1",
    "react": "19.0.0-rc-69d4b800-20241021",
    "react-dom": "19.0.0-rc-69d4b800-20241021",
    ...
  },
  "devDependencies": {
   ...
  },
  "overrides": {
    "recharts": {
      "react-is": "^19.0.0-rc-69d4b800-20241021"
    }
  }
}
  1. Reinstall dependencies: After adjusting the package.json, I reinstalled the dependencies with:
npm install

Conclusion:

These adjustments resolved the chart rendering issues with Recharts on React 19 and Next.js 15. I hope this helps anyone facing the same issue!

agent-Y commented 1 week ago

@matheusvictoor

I have tried that but it does not fix the situation below. Has this problem already been resolved?

so I am trying to make it automatically scale like it would with a responsive container but it doesnt appear if I dont define the width/height I dont understant because in other projects its worked just fine

    <ChartContainer config={chartConfig} className="min-h-[200px] max-h-[400px] w-full">
      <BarChart accessibilityLayer data={chartData} > {/*add width and height to make it appear*/}
        <CartesianGrid vertical={false} />
        <XAxis
          dataKey="day"
          tickLine={false}
          tickMargin={10}
          axisLine={false}
          tickFormatter={(value) => value.slice(0, 3)}
        />
        <ChartTooltip
          cursor={true}
          content={<ChartTooltipContent hideLabel />}
        />
        <Bar dataKey="Submission" fill="var(--color-Submission)" radius={8} />
      </BarChart>
    </ChartContainer>
matheusvictoor commented 1 week ago

@agent-Y

I ran your code and it worked perfectly, the graph rendered and was responsive.

"use client"

import React from 'react';
import { BarChart, Bar, XAxis, CartesianGrid } from 'recharts';
import { ChartContainer, ChartTooltip, ChartTooltipContent } from '@/components/ui/chart';

const chartData = [
  { day: 'Monday', Submission: 30 },
  { day: 'Tuesday', Submission: 45 },
  { day: 'Wednesday', Submission: 50 },
  { day: 'Thursday', Submission: 40 },
  { day: 'Friday', Submission: 70 }
];

const chartConfig = {
  Submission: {
    label: "Submission",
    color: "#8884d8"
  }
};

export function Test() {
  return (
    <ChartContainer config={chartConfig} className="min-h-[200px] max-h-[400px]">
      <BarChart accessibilityLayer data={chartData}>
        <CartesianGrid vertical={false} />
        <XAxis
          dataKey="day"
          tickLine={false}
          tickMargin={10}
          axisLine={false}
          tickFormatter={(value) => value.slice(0, 3)}
        />
        <ChartTooltip cursor={true} content={<ChartTooltipContent hideLabel />} />
        <Bar dataKey="Submission" fill="var(--color-Submission)" radius={8} />
      </BarChart>
    </ChartContainer>
  );
}
agent-Y commented 5 days ago

@matheusvictoor

I have tried that but it does not fix the situation below. Has this problem already been resolved?

so I am trying to make it automatically scale like it would with a responsive container but it doesnt appear if I dont define the width/height I dont understant because in other projects its worked just fine

    <ChartContainer config={chartConfig} className="min-h-[200px] max-h-[400px] w-full">
      <BarChart accessibilityLayer data={chartData} > {/*add width and height to make it appear*/}
        <CartesianGrid vertical={false} />
        <XAxis
          dataKey="day"
          tickLine={false}
          tickMargin={10}
          axisLine={false}
          tickFormatter={(value) => value.slice(0, 3)}
        />
        <ChartTooltip
          cursor={true}
          content={<ChartTooltipContent hideLabel />}
        />
        <Bar dataKey="Submission" fill="var(--color-Submission)" radius={8} />
      </BarChart>
    </ChartContainer>

Fixed by changing the version of recharts to “recharts”:“^2.13.3”.