Friday 11 December 2020

Update child component DOM from parent on animation update

I have set up the following Codepen for reference: Animate React Ref GSAP

I have a React project I'm working on in which, for sake of example, there exist 2 Components: a Pitch (as in a soccer pitch) and a Player. The Pitch is the parent to the Player, and a forwardRef() is used to manage the animation of each player that could be on the pitch from the Pitch component itself.

As you'll also see in the Player component render(). The SVG contains a <g id="Position">...</g> grouping in which the position of the circle should be updated as the animation progresses. This is where I'm at a loss.

In this project I'm using GSAP to manage the animations, but it could be any animation library really - maybe even none if I were to animate by re-render of Player components by state change, but performance may then be a worry. GSAP provides an onUpdate option to its timeline.to() function call. It could be possible to read the position values off the SVG from the ref but it would be bad practice to then try to update its DOM from the parent using ReactDOM.findDOMNode(component) [reference].

Thus, my questions really boil down to this:

  • If it is not best practice to affect the DOM of the child element (I believe it is not even possible from a functional component, according to ESLint on strict) directly from the parent, then how should I manage it?
    • Should the animation be triggered in the child?
    • Or, should I somehow re-render from the state of the parent?

If I haven't made myself perfectly clear please let me know and I'll do my best to clarify anything or everything!



from Update child component DOM from parent on animation update

No comments:

Post a Comment