G
G
gsdev992020-01-29 13:23:25
React
gsdev99, 2020-01-29 13:23:25

What is the correct way to update the gradient in d3.js on re-render?

https://codepen.io/gsdev99/pen/RwNmpoO
Hello everyone. Please tell me how to solve the following problem.
I have an implementation of a graph (curve) with animation. And the implementation of the gradient. When the state changes (in this case, to resize), the curve is normally redrawn, but the problem with the gradient is that its previous state is preserved. How can I save the transition and redraw the gradient?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-01-29
@gsdev99

const Gradient = ({ data, areaGenerator, height }) => {
  const ref = useRef(null);

  useEffect(() => {
    if (ref.current) {
      d3.select(ref.current)
        .append('linearGradient')
        .attr('id', 'area-gradient')
        .attr('gradientUnits', 'userSpaceOnUse')
        .attr('x1', 0)
        .attr('y1', 0)
        .attr('x2', 0)
        .attr('y2', height)
        .selectAll('stop')
        .data([
          { offset: '0%', color: 'rgba(101, 60, 173, 0)' },
          { offset: '100%', color: 'rgba(101, 60, 173, 0.2)' }
        ])
        .enter()
        .append('stop')
        .attr('offset', d => d.offset)
        .attr('stop-color', d => d.color);

      d3.select(ref.current).append('path').attr('class', 'area');
    }
  }, [ ref.current ]);

  useEffect(() => {
    if (ref.current) {
      d3.select(ref.current)
        .select('.area')
        .datum(data)
        .transition()
        .duration(1000)
        .attr('d', areaGenerator);
    }
  }, [ ref.current, data ]);

  return <g className="gradient-generator" ref={ref} />;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question