davidfig / pixi-viewport

A highly configurable viewport/2D camera designed to work with pixi.js
https://davidfig.github.io/pixi-viewport/
MIT License
1.04k stars 174 forks source link

How to use viewport.follow() in react? #279

Open AdrienLemaire opened 3 years ago

AdrienLemaire commented 3 years ago

Using pixi-viewport with react-pixi.

follow() expects a DOM node, which doesn't exist yet when creating the viewport. I can create a ref with useRef and forwardRef for the viewport to access the dom node of the child I want it to follow, but a ref update won't trigger a react re-render, so I'm not sure how/when to do that viewport.follow(childRef.current) call.

One way could be to create a ref on the viewport, and a callback ref on the child to be followed, callback ref that will trigger that call. But that's a lot of refs (poor readability) and that completely binds the logic of the viewport with that of the child (goes against the Separation of concerns principle).

Did someone find a good solution to use pixi-viewport follow method with react ?

AdrienLemaire commented 3 years ago

Here's a working prototype I made: https://codesandbox.io/s/condescending-wave-lkkgs?file=/src/index.js Click on the browser tab, then use the keyboard arrows to move the text with the viewport following it.

The MyViewport component is a nightmare of refs. Any hints to improve this code would be highly appreciated :bowing_man: