react-apexcharts
react-apexcharts copied to clipboard
in this code im using apexcharts to display the data in charts , from api. so i have iconbuttons to change the chart types , so if i change any chart type , it re renders all charts , please provide me solution guys
import React, { useState, useEffect } from 'react'; import Chart from 'react-apexcharts'; import { Card, Grid, IconButton, Tooltip, TextField, Button, Typography, CardHeader, Box, Autocomplete, styled, useTheme, CircularProgress } from '@mui/material'; import { useTranslation } from 'react-i18next'; // import { HelpOutline } from '@mui/icons-material'; import BarChartIcon from '@mui/icons-material/BarChart'; import TimelineIcon from '@mui/icons-material/Timeline'; import PieChartOutlineIcon from '@mui/icons-material/PieChartOutline'; import 'react-datepicker/dist/react-datepicker.css'; import './Styles.css'; import axios from 'axios';
const ChartsNew = () => { const CardHeaderWrapper = styled(CardHeader)( ({ theme }) => ` position: relative;
.MuiCardHeader-action {
position: absolute;
right: ${theme.spacing(3)};
top: ${theme.spacing(3)};
}
`
);
const [chartType, setChartType] = useState('bar'); const [chartType2, setChartType2] = useState('bar2'); const [chartType3, setChartType3] = useState('bar3'); const [chartType4, setChartType4] = useState('bar4'); const [chartData1, setChartData1] = useState([]); const [chartData2, setChartData2] = useState([]); const [chartData3, setChartData3] = useState([]); const [chartData4, setChartData4] = useState([]); const [siteId, setSiteId] = useState('1'); const [year1, setYear1] = useState('2023'); const [loading, setLoading] = useState(true); const theme = useTheme(); const { t } = useTranslation(); const token = localStorage.getItem('jwtToken');
// const scrollRef = useRef();
const fetchData = async () => {
try {
const [response1, response2, response3, response4] = await Promise.all([
axios.get('/ReportApi/BudgetVsActualSummary', {
headers: {
Authorization: Bearer ${token}
, // Include the token in the header
'Content-Type': 'application/json' // Adjust content type if needed
},
params: {
yearId: year1,
// year2: year2,
siteId: siteId || undefined,
type: 'kwh' || undefined
}
}),
axios.get('/ReportApi/BudgetVsActualSummary', {
headers: {
Authorization: Bearer ${token}
, // Include the token in the header
'Content-Type': 'application/json' // Adjust content type if needed
},
params: {
yearId: year1,
// year2: year2,
siteId: siteId || undefined,
type: 'Inr' || undefined
}
}),
axios.get('/ReportApi/BudgetVsActualSummary', {
headers: {
Authorization: Bearer ${token}
, // Include the token in the header
'Content-Type': 'application/json' // Adjust content type if needed
},
params: {
yearId: year1,
// year2: year2,
siteId: siteId || undefined,
type: 'kva' || undefined
}
}),
axios.get('/ReportApi/BudgetVsActualSummary', {
headers: {
Authorization: Bearer ${token}
, // Include the token in the header
'Content-Type': 'application/json' // Adjust content type if needed
},
params: {
yearId: year1,
// year2: year2,
siteId: siteId || undefined,
type: 'hvac' || undefined
// type: type || undefined
}
})
]);
setChartData1(response1.data);
setChartData2(response2.data);
setChartData3(response3.data);
setChartData4(response4.data);
// setChartData5(data5);
// setChartData6(data6);
setLoading(false);
} catch (error) {
console.error('Error fetching data:', error);
}
};
useEffect(() => { fetchData(); }, [siteId]);
const handleChartTypeChange = (type) => { setChartType(type); console.log(type); };
const handleChartTypeChange2 = (type) => { setChartType2(type); console.log(type); };
const handleChartTypeChange3 = (type) => { // Save the current scroll position // const scrollPosition = scrollRef.current.scrollTop; // Change the chart type setChartType3(type); console.log(type); // Scroll back to the previous position // scrollRef.current.scrollTop = scrollPosition; };
const handleChartTypeChange4 = (type) => { setChartType4(type); console.log(type); };
const handleYearChange1 = (event, newValue) => { setYear1(newValue ? newValue.value : ''); };
const BarChart = React.memo(({ chartData }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { background: 'transparent', height: 375, type: 'bar' }, dataLabels: { enabled: false, style: { colors: ['#000000'] } }, colors: [theme.colors.primary.main, theme.colors.warning.main], theme: { mode: theme.palette.mode }, grid: { strokeDashArray: 5, borderColor: theme.palette.divider }, xaxis: { categories: chartData.map((item) => item.monthNo), labels: { style: { colors: chartsTextClass.color // Change this to your desired text color (black in this case) } } // labels: chartData.map((item) => item.category) }, stroke: { width: null }, yaxis: { labels: { style: { colors: chartsTextClass.color // Change this to your desired text color } } }, plotOptions: { bar: { // horizontal: false, columnWidth: '40%', categorySpacing: 2 // distributed: true, // Enable distributed bars } } };
const series = [
{
name: 'Budget' + year1,
type: 'column',
data: chartData.map((item) => item.budget)
},
{
name: 'Actual' + year1,
type: 'area',
// color: '#000',
data: chartData.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
const LineChart = React.memo(({ chartData }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { background: 'transparent', // id: 'realtime', type: 'line' }, xaxis: { categories: chartData.map((item) => item.monthNo), labels: { style: { colors: chartsTextClass.color // Change this to your desired text color (black in this case) } } }, yaxis: { labels: { style: { colors: chartsTextClass.color // Change this to your desired text color } } }, colors: [theme.colors.primary.main, theme.colors.warning.main], theme: { mode: theme.palette.mode }, grid: { strokeDashArray: 5, borderColor: theme.palette.divider }, dataLabels: { enabled: false, style: { colors: ['#000000'] // Change this to your desired text color (black in this case) }, offsetX: 3, background: 'none' }, stroke: { curve: 'smooth' // Use 'smooth' for a smooth curve, remove this line for a straight line } // colors: chartData.map((item) => item.graphColor) // Update with the desired color for the line };
const series = [
{
name: 'Budget' + year1,
data: chartData.map((item) => item.budget)
},
{
name: 'Actual' + year1,
data: chartData.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
// * --------------------------------------------------------------------------------
const BarChart2 = React.memo(({ chartData2 }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { // id: 'basic-bar', background: 'transparent', type: 'bar2' }, dataLabels: { enabled: false }, stroke: { width: null }, xaxis: { categories: chartData2.map((item) => item.monthNo), // labels: chartData.map((item) => item.category) labels: { style: { colors: chartsTextClass.color // Change this to your desired text color (black in this case) } } }, yaxis: { labels: { style: { colors: chartsTextClass.color // Change this to your desired text color } } }, colors: [theme.colors.primary.main, theme.colors.warning.main], theme: { mode: theme.palette.mode }, grid: { strokeDashArray: 5, borderColor: theme.palette.divider }, plotOptions: { bar: { // horizontal: false, columnWidth: '40%', categorySpacing: 2 // distributed: true, // Enable distributed bars } }
// colors: chartData.map((item) => item.graphColor)
};
const series = [
{
name: 'Budget' + year1,
type: 'column',
data: chartData2.map((item) => item.budget)
},
{
name: 'Actual' + year1,
type: 'area',
// color: '#000',
data: chartData2.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
const LineChart2 = React.memo(({ chartData2 }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { background: 'transparent', // id: 'realtime', type: 'line2' }, xaxis: { categories: chartData2.map((item) => item.monthNo), // labels: chartData.map((item) => item.category) labels: { style: { colors: chartsTextClass.color // Change this to your desired text color (black in this case) } } }, dataLabels: { enabled: false, style: { colors: ['#000000'] // Change this to your desired text color (black in this case) }, offsetX: 3, background: 'none' }, colors: [theme.colors.primary.main, theme.colors.warning.main], theme: { mode: theme.palette.mode }, grid: { strokeDashArray: 5, borderColor: theme.palette.divider }, yaxis: { labels: { style: { colors: chartsTextClass.color // Change this to your desired text color } } }
// colors: chartData.map((item) => item.graphColor)
};
const series = [
{
name: 'Budget' + year1,
data: chartData2.map((item) => item.budget)
},
{
name: 'Actual' + year1,
data: chartData2.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
// * --------------------------------------------------------------------------------
const BarChart3 = React.memo(({ chartData3 }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { background: 'transparent', // id: 'basic-bar', type: 'bar3' }, stroke: { width: null }, dataLabels: { enabled: false }, xaxis: { categories: chartData3.map((item) => item.monthNo), // labels: chartData.map((item) => item.category) labels: { style: { colors: chartsTextClass.color // Change this to your desired text color (black in this case) } } }, yaxis: { labels: { style: { colors: chartsTextClass.color // Change this to your desired text color } } }, colors: [theme.colors.primary.main, theme.colors.warning.main], theme: { mode: theme.palette.mode }, grid: { strokeDashArray: 5, borderColor: theme.palette.divider }, plotOptions: { bar: { // horizontal: false, columnWidth: '40%', categorySpacing: 2 // distributed: true, // Enable distributed bars } }
// colors: chartData.map((item) => item.graphColor)
};
const series = [
{
name: 'Budget' + year1,
type: 'column',
data: chartData3.map((item) => item.budget)
},
{
name: 'Actual' + year1,
type: 'area',
// color: '#000',
data: chartData3.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
const LineChart3 = React.memo(({ chartData3 }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { background: 'transparent', // id: 'realtime', type: 'line3' },
xaxis: {
categories: chartData3.map((item) => item.monthNo),
// labels: chartData.map((item) => item.category)
labels: {
style: {
colors: chartsTextClass.color // Change this to your desired text color (black in this case)
}
}
},
yaxis: {
labels: {
style: {
colors: chartsTextClass.color // Change this to your desired text color
}
}
},
stroke: {
curve: 'smooth' // Use 'smooth' for a smooth curve, remove this line for a straight line
},
colors: [theme.colors.primary.main, theme.colors.warning.main],
theme: {
mode: theme.palette.mode
},
grid: {
strokeDashArray: 5,
borderColor: theme.palette.divider
},
dataLabels: {
enabled: false,
style: {
colors: ['#000000'] // Change this to your desired text color (black in this case)
},
offsetX: 3,
background: 'none'
}
// colors: chartData.map((item) => item.graphColor)
};
const series = [
{
name: 'Budget' + year1,
data: chartData3.map((item) => item.budget)
},
{
name: 'Actual' + year1,
data: chartData3.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
// * --------------------------------------------------------------------------------
const BarChart4 = React.memo(({ chartData4 }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { background: 'transparent', // id: 'basic-bar', type: 'bar4' }, dataLabels: { enabled: false }, xaxis: { categories: chartData4.map((item) => item.monthNo), // labels: chartData.map((item) => item.category) labels: { style: { colors: chartsTextClass.color // Change this to your desired text color (black in this case) } } }, colors: [theme.colors.primary.main, theme.colors.warning.main], theme: { mode: theme.palette.mode }, grid: { strokeDashArray: 5, borderColor: theme.palette.divider }, yaxis: { labels: { style: { colors: chartsTextClass.color // Change this to your desired text color } } }, stroke: { width: null }, plotOptions: { bar: { // horizontal: false, columnWidth: '40%', categorySpacing: 2 // distributed: true, // Enable distributed bars } } };
const series = [
{
name: 'Budget' + year1,
type: 'column',
data: chartData4.map((item) => item.budget)
},
{
name: 'Actual' + year1,
type: 'area',
// color: '#000',
data: chartData4.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
const LineChart4 = React.memo(({ chartData4 }) => { const chartsTextClass = { color: theme.palette.text.secondary // Change this to your desired text color }; const options = { chart: { background: 'transparent', // id: 'realtime', type: 'line4' }, xaxis: { categories: chartData4.map((item) => item.monthNo), labels: { style: { colors: chartsTextClass.color // Change this to your desired text color (black in this case) } } }, colors: [theme.colors.primary.main, theme.colors.warning.main], theme: { mode: theme.palette.mode }, grid: { strokeDashArray: 5, borderColor: theme.palette.divider }, yaxis: { labels: { style: { colors: chartsTextClass.color // Change this to your desired text color } } }, stroke: { curve: 'smooth' // Use 'smooth' for a smooth curve, remove this line for a straight line }, dataLabels: { enabled: false, style: { colors: ['#000000'] // Change this to your desired text color (black in this case) }, offsetX: 3, background: 'none' } // colors: chartData.map((item) => item.graphColor) // Update with the desired color for the line };
const series = [
{
name: 'Budget' + year1,
data: chartData4.map((item) => item.budget)
},
{
name: 'Actual' + year1,
data: chartData4.map((item) => item.actualKva)
}
];
return <Chart options={options} series={series} type="area" height={375} />;
});
const handleSiteIdChange = (event, newValue) => { setSiteId(newValue ? newValue.value : ''); };
const handleClear = () => { setYear1(''); setSiteId(''); };
const SelectYears1 = [ { label: '2018', value: '2018' }, { label: '2019', value: '2019' }, { label: '2020', value: '2020' }, { label: '2021', value: '2021' }, { label: '2022', value: '2022' }, { label: '2023', value: '2023' }, { label: '2024', value: '2024' }, { label: '2025', value: '2025' }, { label: '2026', value: '2026' }, { label: '2027', value: '2027' }, { label: '2028', value: '2028' }, { label: '2029', value: '2029' }, { label: '2030', value: '2030' }, { label: '2031', value: '2031' }, { label: '2032', value: '2032' } ];
const SelectSites = [ { label: 'Indiqube AMR Tech park', value: '1' }, { label: 'Indiqube Ashford', value: '2' }, { label: 'Indiqube Aura', value: '3' }, { label: 'Indiqube Golf View', value: '4' }, { label: 'Indiqube Ocean', value: '5' }, { label: 'Indiqube Orion', value: '6' }, { label: 'IndiQube Pearl', value: '7' }, { label: 'Indiqube Prime', value: '8' }, { label: 'Indiqube Amar Apex', value: '9' } ];
return (
<Grid item xs={12} sm={2}>
<Box p={1}>
<Autocomplete
disablePortal
options={SelectYears1}
getOptionLabel={(option) => option.label}
value={
SelectYears1.find((option) => option.value === year1) ||
null
}
onChange={handleYearChange1}
renderInput={(params) => (
<TextField
{...params}
label={'Select Year '}
fullWidth
// onChange={handleYearChange}
// value={year}
/>
)}
/>
</Box>
</Grid>
<Grid
item
xs={12}
sm={6.9}
sx={{ display: 'flex', justifyContent: 'flex-end' }}
>
<Button
variant="contained"
onClick={() => {
fetchData();
// setIsViewClicked(true);
}}
>
View
</Button>
<Button
variant="contained"
onClick={handleClear}
sx={{ marginLeft: '10px' }}
>
Clear
</Button>
</Grid>
</Grid>
</Card>
<Grid
// ref={scrollRef}
sx={{
px: 2.5
// display: isViewClicked ? 'column' : 'none'
}}
container
direction="row"
// alignItems="stretch"
spacing={1}
>
{/* xs={12} */}
<Grid item md={6} xs={12}>
<Card sx={{ mb: 2.5, ml: -1.5, mt: -1 }}>
<CardHeaderWrapper
disableTypography
sx={{
p: 3
}}
title={
<Typography
className="Headertext"
component="div"
sx={{
fontSize: `${theme.typography.pxToRem(17)}`
}}
textAlign="left"
gutterBottom
variant="h3"
>
{t('Electricity In KWH')}
</Typography>
}
/>
<div
className="Chart-Button"
style={{
display: 'flex',
justifyContent: 'flex-end',
marginTop: '-68px'
}}
>
<Tooltip title="Bar Chart">
<IconButton
onClick={() => {
handleChartTypeChange('bar');
}}
>
<BarChartIcon />
</IconButton>
</Tooltip>
<Tooltip title="Line Chart">
<IconButton
onClick={() => {
handleChartTypeChange('line');
}}
>
<TimelineIcon />
</IconButton>
</Tooltip>
<Tooltip title="Pie Chart">
<IconButton
onClick={() => {
handleChartTypeChange('pie');
}}
>
<PieChartOutlineIcon sx={{ display: 'none' }} />
</IconButton>
</Tooltip>
</div>
<div>
{chartType === 'bar' && <BarChart chartData={chartData1} />}
{chartType === 'line' && <LineChart chartData={chartData1} />}
{/* {chartType === 'pie' && <PieChart chartData={chartData1} />} */}
</div>
</Card>
</Grid>
{/* // * ------------------------------------------------- second card ----------------------------------------- */}
<Grid item md={6}>
<Card sx={{ mb: 2.5, mr: -1.5, mt: -1 }}>
<CardHeaderWrapper
disableTypography
sx={{
p: 3
}}
title={
<Typography
className="Headertext"
component="div"
sx={{
fontSize: `${theme.typography.pxToRem(17)}`
}}
textAlign="left"
gutterBottom
variant="h3"
>
{t('Energy Cost In INR')}
</Typography>
}
/>
<div
className="Chart-Button"
style={{
display: 'flex',
justifyContent: 'flex-end',
marginTop: '-68px'
}}
>
<Tooltip title="Bar Chart">
<IconButton
onClick={() => {
handleChartTypeChange2('bar2');
}}
>
<BarChartIcon />
</IconButton>
</Tooltip>
<Tooltip title="Line Chart">
<IconButton
onClick={() => {
handleChartTypeChange2('line2');
}}
>
<TimelineIcon />
</IconButton>
</Tooltip>
<Tooltip title="Pie Chart">
<IconButton
onClick={() => {
handleChartTypeChange2('pie');
}}
>
<PieChartOutlineIcon sx={{ display: 'none' }} />
</IconButton>
</Tooltip>
</div>
<div>
{chartType2 === 'bar2' && (
<BarChart2 chartData2={chartData2} />
)}
{chartType2 === 'line2' && (
<LineChart2 chartData2={chartData2} />
)}
{/* {chartType2 === 'pie' && <PieChart2 chartData={chartData2} />} */}
</div>
</Card>
</Grid>
{/* // * ------------------------------------------------- third card ----------------------------------------- */}
<Grid item md={6}>
<Card
className="sample-card"
sx={{ mb: 2.5, ml: -1.5, mt: -2.5 }}
>
<CardHeaderWrapper
disableTypography
sx={{
p: 3
}}
title={
<Typography
className="Headertext"
component="div"
sx={{
fontSize: `${theme.typography.pxToRem(17)}`
}}
textAlign="left"
gutterBottom
variant="h3"
>
{t('Maximum Demand In KVA')}
</Typography>
}
/>
<div
className="Chart-Button"
style={{
display: 'flex',
justifyContent: 'flex-end',
marginTop: '-68px'
}}
>
<Tooltip title="Bar Chart">
<IconButton
onClick={() => {
handleChartTypeChange3('bar3');
}}
>
<BarChartIcon />
</IconButton>
</Tooltip>
<Tooltip title="Line Chart">
<IconButton
onClick={() => {
handleChartTypeChange3('line3');
}}
>
<TimelineIcon />
</IconButton>
</Tooltip>
<Tooltip title="Pie Chart">
<IconButton
onClick={() => {
handleChartTypeChange3('pie3');
}}
>
<PieChartOutlineIcon sx={{ display: 'none' }} />
</IconButton>
</Tooltip>
</div>
{/* className="all-charts" */}
<div>
{chartType3 === 'bar3' && (
<BarChart3 chartData3={chartData3} />
)}
{chartType3 === 'line3' && (
<LineChart3 chartData3={chartData3} />
)}
{/* {chartType3 === 'pie' && <PieChart3 chartData={chartData3} />} */}
</div>
</Card>
</Grid>
{/* // * ------------------------------------------------- Fourth card ----------------------------------------- */}
<Grid item md={6}>
<Card
className="sample-card"
sx={{ mb: 2.5, mr: -1.5, mt: -2.5 }}
>
<CardHeaderWrapper
disableTypography
sx={{
p: 3
}}
title={
<Typography
className="Headertext"
component="div"
sx={{
fontSize: `${theme.typography.pxToRem(17)}`
}}
textAlign="left"
gutterBottom
variant="h3"
>
{t('HVAC Consumption In KWH')}
</Typography>
}
/>
<div
className="Chart-Button"
style={{
display: 'flex',
justifyContent: 'flex-end',
marginTop: '-68px'
}}
>
<Tooltip title="Bar Chart">
<IconButton
onClick={() => {
handleChartTypeChange4('bar4');
}}
>
<BarChartIcon />
</IconButton>
</Tooltip>
<Tooltip title="Line Chart">
<IconButton
onClick={() => {
handleChartTypeChange4('line4');
}}
>
<TimelineIcon />
</IconButton>
</Tooltip>
<Tooltip title="Pie Chart">
<IconButton
onClick={() => {
handleChartTypeChange4('pie');
}}
>
<PieChartOutlineIcon sx={{ display: 'none' }} />
</IconButton>
</Tooltip>
</div>
<div>
{chartType4 === 'bar4' && (
<BarChart4 chartData4={chartData4} />
)}
{chartType4 === 'line4' && (
<LineChart4 chartData4={chartData4} />
)}
{/* {chartType4 === 'pie' && <PieChart4 chartData={chartData4} />} */}
</div>
</Card>
</Grid>
</Grid>
</>
)}
</div>
); };
export default ChartsNew;