Search code examples
reactjsrecharts

Is there a way to change a value based upon activeDot in Rechart?


I currently am creating a chart in recharts as follows:

      <h3>Stock</h3>
      <h3>TARGET POINT TO CHANGE HERE</h3>
      <div class="chartContainer">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart
          width={800}
          height={250}
          data={data}
          margin={{
            top: 5,
            right: 30,
            left: 20,
            bottom: 5,
          }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="date" tick={false} />
          <YAxis dataKey="close" tick={false} domain={[low, high]} />
          <Tooltip />
          <Line type="monotone" dataKey="close" stroke="turquoise" activeDot={{ r: 4 }} />
        </LineChart>
      </ResponsiveContainer>
      </div>

I'm hoping to change the value of the TARGET POINT TO CHANGE HERE to be the y value of whatever the activeDot is hovering over (similar to RobinHood). Anyone know how to do this?


Solution

  • Create a useState hook to store the y value:

    const [value, setValue] = useState("")

    Add a trigger to the LineChart that will update the value and change the h3:

     <h3>Stock</h3>
      <h3>{value}</h3>
      <div class="chartContainer">
      <ResponsiveContainer width="100%" height="100%">
        <LineChart
          width={800}
          height={250}
          data={data}
          margin={{
            top: 5,
            right: 30,
            left: 20,
            bottom: 5,
          }}
          onMouseMove={e => { 
           setValue(e.activePayload[0].value)
          }}
        >
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="date" tick={false} />
          <YAxis dataKey="close" tick={false} domain={[low, high]} />
          <Tooltip />
          <Line type="monotone" dataKey="close" stroke="turquoise" activeDot={{ r: 4 }} />
        </LineChart>
      </ResponsiveContainer>
      </div>