javascript – React chart Js2 and Material table not resizing after a page resize

I am developing a single page application with React, in which I have a landing page that works as a dashboard with graphs and a summary table. Both the table and the graphs are enclosed within the basic components <Card> and <CardContent>.

However, I have the following problem, when I resize the page, or simply set the browser to view it from a mobile device, the card resizes correctly, while the content inside does not. In particular, when the screen is resized, by reloading the page the graphs are then correctly rendered resized, while the table with the final balances is not. I would like it all to be responsive as I reduce the screen size.

Do you have any suggestions or advice? Am I doing something wrong? I state that I am quite new to programming with React.

Thanks in advance!

CODE:

import React, { useEffect, useState } from "react";
import Grid from "@material-ui/core/Grid";
import DashCard from "./DashboardCard" // eliminabile
import HomeDoughChart from '../charts_js/HomeDoughChart'
import HomeBarChart from "../charts_js/HomeBarChart";
import MaterialTable from "material-table";
import { getDashboard_Data, getDashboard_Data_byYear, getDashboard_TributeFiler, getDashboard_YearFiler } from "../../repo/dashboardRepo";
import { Card, CardContent } from "@material-ui/core";

const DashboardContent = () => {
   const [chart, setChart] = useState([])
   const [barchart, setBarChart] = useState([])
   const [trib, setTributi] = useState([])
   const [year, setAnni] = useState([])
   const [dashboardfilter, setDashboardFilter] = useState({ year: "", tributo: "" });
   function handleYearChange(evt) {
      setDashboardFilter({ year: evt.target.value, tributo: dashboardfilter.tributo });
      const yf = async () => {
         const res = (dashboardfilter.year !== "") ? await getDashboard_Data_byYear(dashboardfilter.year) : await getDashboard_Data();
         setChart(res.data.data);
      }
      yf();
   }

   function handleTributeChange(evt) {
      setDashboardFilter({ year: dashboardfilter.year, tributo: evt.target.value });
      const yf = async () => {
         const res = await getDashboard_Data_byYear(dashboardfilter.year);
         setChart(res.data.data);
      }
      yf();
   }

   useEffect(() => {
      const a = async () => {
         if (dashboardfilter.year === "" && dashboardfilter.tributo === "") {
            const res = await getDashboard_Data();
            setChart(res.data.data);
         }
      }
      a()
   }, [])

   useEffect(() => {
      const b = async () => {
         const res1 = await getDashboard_Data_byYear();
         setBarChart(res1.data.data);
      }
      b()
   }, [])

   useEffect(() => {
      const c = async () => {
         const res2 = await getDashboard_TributeFiler();
         const res3 = await getDashboard_YearFiler();
         setTributi(res2.data.data);
         setAnni(res3.data.data);
      }
      c();
   }, [])

   return (
      <div>
         <Card style={{ marginLeft: 30, responsive: true, marginTop: 50, marginRight: 30 }}>
            <CardContent>
               <Grid container direction="row" justify="left" alignItems="center" >
                  <div style={{ display: "flex", alignItems: "stretch" }}>
                     <form>
                        <label>Filtra per anno di riferimento</label>
                        <select name="year" value={dashboardfilter.year} onChange={handleYearChange}>
                           <option value="">Tutti gli anni</option>
                           {year.map(y => {
                              return (
                                 <option key={y.anno} value={y.anno}>
                                    {y.anno}
                                 </option>
                              )
                           })}
                        </select>
                        <br />
                        <label>Filtra per tributo</label>
                        <select name="tributo" value={dashboardfilter.tributo} onChange={handleTributeChange}>
                           <option value="">Tutti i tributi</option>
                           {trib.map(tributi => {
                              return (
                                 <option key={tributi.codiceTributo} value={tributi.codiceTributo}>
                                    {tributi.descrizioneServizio}
                                 </option>
                              )
                           })}
                        </select>
                     </form>
                     {console.log("Anno:" + dashboardfilter.year + " Tributo:" + dashboardfilter.tributo)}
                     <HomeDoughChart chart={chart} />
                     <Grid container spacing={1} style={{ marginTop: '50px', marginLeft: '20px' }}>
                        <MaterialTable
                           options={{
                              search: false,
                              paging: false,
                              sorting: false,
                           }}
                           columns={[
                              { title: '', field: 'name' },
                              { title: 'Importo €', field: 'importo' },
                              { title: 'Atti', field: 'atti', type: 'numeric' },
                              { title: '%', field: 'percentage' }
                           ]}
                           data={[
                              { name: 'Totale pendenze', importo: Intl.NumberFormat('it-IT', { style: 'currency', currency: 'EUR' }).format(chart.totaleDaPagare), atti: chart.attiTotali, percentage: '100%' },
                              { name: 'Totale pagamenti', importo: Intl.NumberFormat('it-IT', { style: 'currency', currency: 'EUR' }).format(chart.totalePagato), atti: chart.pendenzePagate, percentage: parseFloat((chart.totalePagato * 100) / chart.totaleDaPagare).toFixed(2) },
                              { name: 'Rimanente', importo: Intl.NumberFormat('it-IT', { style: 'currency', currency: 'EUR' }).format(chart.totaleNonPagato), atti: chart.pendenzeNonPagate, percentage: parseFloat((chart.totaleNonPagato * 100) / chart.totaleDaPagare).toFixed(2) },
                              { name: 'Non agganciato', importo: Intl.NumberFormat('it-IT', { style: 'currency', currency: 'EUR' }).format(chart.totaleParziali), atti: chart.pendenzeParziali, percentage: parseFloat((chart.totaleParziali * 100) / chart.totaleDaPagare).toFixed(2) },

                           ]}
                           title="Consuntivo posizioni" />
                     </Grid>
                  </div>
               </Grid>
               <Grid container direction="row" justify="left" alignItems="center" style={{ marginTop: '70px', marginLeft: '20px' }}>
                  <p>Consuntivi per anno</p>
                  <HomeBarChart barchart={barchart} />
               </Grid>
            </CardContent>
         </Card>

      </div>
   )
}
export default DashboardContent;
import PageTemplate from "../templates/Template";
import React from "react";
import DashboardContent from "./DashboardContent";

const DashboardPageNew = () => {
   return (
      <PageTemplate title={"Homepage del comune di '" + localStorage.getItem("tenant") + "'"}>
         <DashboardContent />
      </PageTemplate>
   )
}
export default DashboardPageNew;
import React from 'react';
import {
   Chart as ChartJS,
   CategoryScale,
   LinearScale,
   BarElement,
   Title,
   Tooltip,
   Legend,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';

ChartJS.register(
   CategoryScale,
   LinearScale,
   BarElement,
   Title,
   Tooltip,
   Legend
);

export const options = {
   responsive: true,
   plugins: {
      legend: {
         position: 'top',
      },
      title: {
         display: true,
         text: 'Chart.js Bar Chart',
      },
   },
};
var today = new Date();
const year = today.getFullYear()
const labels = ['Anno '+year, 'Anno '+(year-1), 'Anno '+(year-2), 'Anno '+(year-3)];

const HomeBarChart = (props) => {
   return (
      <div style={{ width: window.innerWidth / 2, height: window.innerHeight / 2 }}>
         <Bar data={{
            labels,
            datasets: [
               {
                  label: 'Dovuto',
                  data: [10,20,30,40],
                  backgroundColor: 'rgba(255, 99, 132, 0.5)',
               },
               {
                  label: 'Pagato',
                  data: [10,20,30,40],
                  backgroundColor: 'rgba(53, 162, 235, 0.5)',
               },
               {
                  label: 'Non collegato',
                  data: [10,20,30,40],
                  backgroundColor: 'rgba(255, 206, 86, 0.2)',
               },
               {
                  label: 'Rimanente',
                  data: [10,20,30,40],
                  backgroundColor: 'rgba(0,0,0,0.4)',
               },
            ],
         }} options={{ title: { display: true, text: 'My text' }, responsive: true }} style={{ marginTop: '80px', marginLeft: '10px' }} />
      </div>
   );
}
export default HomeBarChart;

import React from 'react';
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js';
import { Doughnut } from 'react-chartjs-2';

ChartJS.register(ArcElement, Tooltip, Legend);

const HomePieChart = (props) => {

  return (
    <div style={{ width: window.innerWidth / 2, height: window.innerHeight / 2 }}>
      <h1>Totale da riscuotere: {Intl.NumberFormat('it-IT', { style: 'currency', currency: 'EUR' }).format(props.chart.totaleDaPagare)} </h1>
      <Doughnut data={{
        labels: ['Pagato', 'Non Pagato', 'Parziali'],
        datasets: [
          {
            label: 'Pagamenti',
            data: [ props.chart.totalePagato, props.chart.totaleNonPagato, props.chart.totaleParziali],
            backgroundColor: [
              'rgba(144, 245, 181, 0.2)',
              'rgba(200, 12, 95, 0.2)',
              'rgba(237, 192, 95, 0.2)',
            ],
            borderColor: [
              'rgba(144, 245, 181, 1)',
              'rgba(200, 12, 95, 0.2)',
              'rgba(237, 192, 95, 1)',
            ],
            borderWidth: 1,
          },
        ],
      }} options={{ responsive: true }} style={{ marginTop: '20px', marginLeft: '10px' }} />
    </div>
  );
}

export default HomePieChart;

Leave a Comment