reactjsrecharts

How change bar fill color on hover in recharts?


I have a bar chart with bars that are filled according to their y-value. How can I change the background color on hover?

red -> purple green -> blue

Sandbox

export default function App() {
  const colorizeBars = (data) => {
    const coloredData = data.map((bar) => {
      if (bar.uv > 3000) {
        return { ...bar, fill: "#00ff00" };
      } else {
        return { ...bar, fill: "#ff0000" };
      }
    });
    return coloredData;
  };
  const coloredData = colorizeBars(data);
  return (
    <div style={{ height: 300 }}>
      <ResponsiveContainer width="100%" height="100%">
        <BarChart
          width="100%"
          height={300}
          data={coloredData}
          margin={{
            top: 50,
            right: 30,
            left: 20,
            bottom: 5,
          }}
        >
          <XAxis
            dataKey="name"
            tickLine={false}
            style={{
              fontSize: 14,
              color: "#000000",
              fontFamily: "Arial",
              fontWeight: "bold",
            }}
          />
          <YAxis tickLine={false} />
          <Tooltip />
          <Legend />
          <Bar dataKey="uv" label={<CustomizedLabel />} />
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

Solution

  • Not sure if this is the best way but this is how i did it. i modified the Bar component props to

    <Bar
      dataKey="uv"
      label={<CustomizedLabel />}
      shape={(props) => (
        <rect
          {...props}
          onMouseEnter={() => setHover(props.index)}
          onMouseLeave={() => setHover(null)}
          fill={hover === props.index ? "#ff5100" : props.payload.fill}
        />
      )}
    />
    
    

    now all we need to do is add a state to track the hovered bar

    const [hover, setHover] = useState();
    

    hope this helps

    EDIT to not loose the default styling you put in place i changed the fill to props.payload.fill