I am using chart.js in reaction to create line chart. I want to show the day and month data like Aug 25, Jul 16. I don't know how to change the format of this data downloaded from the API. Please help. Here is my code thank you for the hints
Is there a proper way to format dates for data labels in Chart.JS?
import axios from 'axios';
import { useParams } from 'react-router-dom';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const rate = axios.create({
baseURL: 'http://api.nbp.pl/api/exchangerates/rates/a/',
});
const Chart = () => {
const [post, setPost] = useState();
const { id } = useParams();
useEffect(() => {
async function getPost() {
const response = await rate.get(`/${id}/last/10/?format=json`);
setPost(response.data);
}
getPost();
}, [id]);
const data = {
type: 'line',
labels: post?.rates?.map((x) => x.effectiveDate),
datasets: [
{
label: `Ostatnie 10 odczytów`,
data: post?.rates?.map((y) => y.mid),
lineTension: 0.1,
backgroundColor: 'rgba(15, 174, 150)',
borderColor: 'rgba(15, 174, 150)',
gridLines: 'false',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(15, 174, 150)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(15, 174, 150)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
},
],
options: {
responsive: true,
},
};
return (
<div
style={{
width: '800px',
height: '800px',
margin: '0px auto',
paddingTop: '500px',
}}
>
<Line data={data} />
</div>
);
};
export default Chart;
CodePudding user response:
Welcome, Veronica! If you don't want to use a third-party package, I would advise working with the Date
type along with the Intl.DateTimeFormat
object. Once you've cast to Date
, you can build the desired string.
post?.rates?.map(x => {
date = new Date(x.effectiveDate);
return new Intl.DateTimeFormat('en-US', {
month: 'short',
day: 'numeric',
}).format(date);
});
CodePudding user response:
Hi I think you can use moment or dayjs(same stuff and moment since its depricated suggested dayjs) for this like post?.rates?.map((x) => moment(x.effectiveDate).format('the format you want))