简体   繁体   中英

One common component for Chart.js to use with different y-axis With React.js

useEffect(() => {
    let ctx = document.getElementById("LineChart");
    const blue = [2000, 2100, 2400, 2450, 3000];
    const yellow = [1800, 2150, 2550, 2800, 2000];
    const pink = [1200, 1100, 1050, 1010, 1000];

    const LineChart = new Chart(ctx, {
      type: "line",
      data: {
        labels: ["Jan", "Feb", "Mar", "Apr", "May"],

        datasets: [
          {
            data: blue,
            label: "New MRR",
            fill: false,
            lineTension: 0.5,
            backgroundColor: "#3ea5e0",
            borderColor: "#3ea5e0",
            pointBorderWidth: 1,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointRadius: 1,
            pointHitRadius: 10,
          },
          {
            data: yellow,
            label: "Net New MRR",
            fill: false,
            lineTension: 0.5,
            backgroundColor: "#ad9a52",
            borderColor: "#ad9a52",
            pointBorderWidth: 1,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointRadius: 1,
            pointHitRadius: 10,
          },
          {
            data: pink,
            label: "Lost MRR",
            fill: false,
            lineTension: 0.5,
            backgroundColor: "#5c3784",
            borderColor: "#5c3784",
            pointBorderWidth: 1,
            pointHoverBackgroundColor: "rgba(75,192,192,1)",
            pointRadius: 1,
            pointHitRadius: 10,
          },
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                beginAtZero: false,
                callback: function (value, index, values) {
                  return "$" + value;
                },
              },
            },
          ],
        },
      },
    });

    let ctx2 = document.getElementById("BarChart");
    const BarChart = new Chart(ctx2, {
      type: "bar",
      data: data,
    });

I want to create a common chart component with same x-axis values but different y-axis values.I have switch case according to their type.So I can render charts with their types.Is there a short way to create a common chart or do I have to code all of them? Because right now I can only render one line chart.

Here is how you can create a common Chart component which will draw the chart given a custom data.

https://codesandbox.io/s/serverless-frog-6bu2f?file=/src/App.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM