I'm new to the apexchart and reactjs, don't know how to display series based on the no. of messages of a particular month instead of giving static data. I've gone through this link "ApexCharts barchart vertical categories logic in ReactJs?" but unable to put the logic correctly.
This is the Code
import React, { Component } from "react";
import Chart from "react-apexcharts";
import { messages } from "../constants/constant";
class Donut extends Component {
constructor() {
super();
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(res => res.json())
.then(res => {
// Setting the response
// this.props.setMessages(messages);
// this.props.stareMessages();
console.log("messages", messages);
this.setState({
messages: messages
});
});
}
state = {
index: 0,
flag: false,
messages: [],
options: {
labels: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
chart: {
height: 350,
type: "bar",
events: {
dataPointSelection: (event, chartContext, config) => {
this.setState({
labels: chartContext.opts.labels,
percentage: chartContext.opts.series
});
const selectedData = messages.find(
x => x.id === config.dataPointIndex + 1
);
this.setState({ flag: true, selectedData });
}
}
},
legend: {
position: "bottom",
horizontalAlign: "center"
}
},
series: [44, 55, 41, 17, 15, 50, 79, 46, 78, 96, 78, 100]
};
render() {
const { selectedData, options, series } = this.state;
return (
<div className="donut">
<Chart options={options} series={series} type="donut" width="380" />
{selectedData && (
<table className="table">
<thead>
<tr>
<th width="200">From</th>
<th width="200">To</th>
<th width="200">Date & Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>{selectedData.from}</td>
<td>{selectedData.to}</td>
<td>{selectedData.date}</td>
</tr>
</tbody>
</table>
)}
</div>
);
}
}
export default Donut;
You can use momentjs to parse your date format.
I'm pretty sure it can be optimized. I'd say the best optimization is to already receive the data in correct format.
const countEmailsByMonth = data => {
const dates = data.map(datum =>
moment(datum.date, ["DD-MM-YYYY"]).format("MMMM")
);
// getting our dates from your message json file
//and formatting them to display month
const months = moment.months();
// getting 12 months arr from moment.js
const mergedMonths = [...months, ...dates];
// merging months and dates together
const sortedMonths = mergedMonths.sort(
(a, b) => months.indexOf(a) - months.indexOf(b)
);
//sorting months
const chartData = {};
//counting duplicates
sortedMonths.map(val => (chartData[val] = chartData[val] + 1 || 0));
return chartData;
};
here is link to codesandbox