I have just started out using Recharts and am a total beginner. I have managed to render a chart, customise some styling, such as color of the bars and position of the legend, but I am now struggling to customise the dataKey values.
At the moment, the chart looks like this: https://i.stack.imgur.com/glBKE.png
I am trying to render a BarChart from the following data:
const data = [
{day: "2020-07-01", kilogram: 80, calories: 240},
{day: "2020-07-02", kilogram: 80, calories: 240},
{day: "2020-07-03", kilogram: 80, calories: 240},
{day: "2020-07-04", kilogram: 80, calories: 240},
{day: "2020-07-05", kilogram: 80, calories: 240}
];
Setting the dataKey on the <XAxis> component to "day" works fine, but the ticks display the full string. Instead, I would like to only display the day of the month. So instead of saying "2020-07-01", it should only say "1".
I have already tried the following two things:
- I have added this function to the render method, to calculate the day and set this as the dataKey value.
let dataKeyValue = (x) => {
let value = x.day;
value = value.getDate();
value = value.toString();
return value;
};
- I have added this method to the component, to format the tick.
axisTickFormatter(day) {
const date = new Date(day);
const dataKey = date.getDate();
dataKey.toString();
console.log(typeof dataKey);
return dataKey;
}
=> you can see both in the code below - commented out
This is my code:
class Chart extends React.Component {
constructor(props) {
super(props);
this.type = this.props.type;
this.data = this.props.data;
}
// axisTickFormatter(day) {
// const date = new Date(day);
// const dataKey = date.getDate();
// dataKey.toString();
// console.log(typeof dataKey);
// return dataKey;
// }
render() {
// let dataKeyValue = (x) => {
// let value = x.day;
// value = value.getDate();
// value = value.toString();
// return value;
//};
return (
<ResponsiveContainer>
<BarChart
width={730}
height={250}
data={this.data.sessions}
barCategoryGap={8}
barSize={7}
>
<CartesianGrid strokeDasharray="2 2" vertical={false} />
<XAxis dataKey="day" />
{/* <XAxis dataKey={(day) => this.axisTickFormatter(day)} /> */}
{/* <XAxis dataKey={dataKeyValue} /> */}
<YAxis />
<Tooltip />
<Legend
iconSize={8}
iconType="circle"
verticalAlign="top"
align="right"
/>
<Bar dataKey="kilogram" fill="#282D30" radius={[3, 3, 0, 0]} />
<Bar dataKey="calories" fill="#E60000" radius={[3, 3, 0, 0]} />
</BarChart>
</ResponsiveContainer>
)
}
}
Could you give me a hint as to what I am forgetting or doing wrong?