What I would like to achieve is this:
How do I configure the CartesianGrid to have dashes on the horizontal axis and a solid line on the vertical axis?
As far as I can see, there is no simple solution, based on configuration options. A hacky solution can be implemented by changing the grid lines at either ends: when they are created (the solution below) or after they are rendered - the grid line in the resulting svg may be accessed as .recharts-cartesian-grid-horizontal > line
and those lines need to have their stroke-dasharray
properties altered.
So, a possible solution is to extend the class CartesianGrid
. Below is a quick solution that only addresses the question as asked; one can extend that to a complex grid class that has different properties for the vertical and horizontal lines. The reference for that should come from the source code: CartesianGrid.tsx.
The class that changes the stroke-dasharray
for the vertical axis could be implemented as (tsx):
class CartesianGridNoDashVertical extends CartesianGrid {
renderVertical(verticalPoints: number[]): JSX.Element {
const element = super.renderVertical(verticalPoints);
const lines = element.props.children.map((el: JSX.Element) =>
React.cloneElement(el, { strokeDasharray: "0" })
);
return React.cloneElement(element, [], lines);
}
}
and used instead of the standard grid element in the markup:
<LineChart
width={500}
height={300}
data={data}
>
<CartesianGridNoDashVertical strokeDasharray="3 3" />
<XAxis />
<YAxis />
</LineChart>
Here' a sandbox forked from a standard recharts example.