Search code examples
reactjslinechartrecharts

Recharts click between points


I've a linechart (from Recharts, React) made of N points and I want to set a ReferenceLine at a specific X.

When I set manually the X value for the ReferenceLine, it's everything ok (e.g., x={35}), while if I click on the linechart, the ReferenceLine is automatically drawn at the nearest X.

How to solve this issue?

import { Line, LineChart, ReferenceLine, XAxis, YAxis } from "recharts";
import React from "react";
import {useState} from "react";


function App() {

    function handleClick(event) {
        //console.log(event);
        setLine(event.activeLabel)
    }

    const data = [
        {
            tag: 0,
            value: 10
        },
        {
            tag: 10,
            value: 10
        },
        {
            tag: 20,
            value: 30
        },
        {
            tag: 50,
            value: 20
        },
        {
            tag: 100,
            value: 10
        }
    ];

    const [line, setLine] = useState();

    return (
    
        <LineChart 
        data={data} 
        onClick={(event) => handleClick(event)} 
        width={500} 
        height={300}>
        
            <XAxis
                dataKey="tag"
                scale="linear"
                tick={true}
                type="number"
                domain={[0, 100]}
            />
            <YAxis  />

            <Line
                type="monotone"
                dataKey="value"
                stroke="black"
                strokeWidth={3}
                dot={true}
            />
            <ReferenceLine
                x={line}
                //x={35}
                stroke={"black"}
                strokeWidth={1}
                strokeDasharray="3 3"
            />
            
        </LineChart>
    );
}

export default App;


Solution

  • You can pass custom scale prop from d3-scale package as described in documentation here.

    const scale = scaleLinear().domain([0, 100])
    

    Then assign to your XAxis component:

    <XAxis
      ...
      scale={scale}
      ticks={scale.ticks()}
    />
    

    Then when there is a click event, convert the chartX value to x-axis scale:

    scale.invert(event.chartX)
    

    Related answer from Github.

    Edit quirky-wood-ght21l