pixijs / pixi-react

Write PIXI apps using React declarative style
https://pixijs.io/pixi-react/
MIT License
2.36k stars 179 forks source link

Feature Request: Please include examples about Custom Components using High Order Components #460

Open jdnichollsc opened 11 months ago

jdnichollsc commented 11 months ago

Description

Hello folks, hope you're doing!

This lib is amazing, thanks for sharing this project with the community!

About my request, it would be great to include examples in the docs/website about using High Order Components while creating custom components, please check my below example and let me know what you think! <3

let index = 1; export function withPixiDraggable( WrappedComponent: ComponentType ): ComponentType { return function (props) { const containerRef = useRef(); const isDragging = useRef(false); const offset = useRef({ x: 0, y: 0 }); const [position, setPosition] = useState({ x: props.x || (props.position ? props.position[0] : 0) || 0, y: props.y || (props.position ? props.position[1] : 0) || 0, }); const [alpha, setAlpha] = useState(1); const [zIndex, setZIndex] = useState(index);

function onStart(e: FederatedPointerEvent) {
  isDragging.current = true;
  offset.current = {
    x: e.data.global.x - position.x,
    y: e.data.global.y - position.y,
  };

  setAlpha(0.5);
  setZIndex(index++);
}

function onEnd() {
  isDragging.current = false;
  setAlpha(1);
}

function onMove(e: FederatedPointerEvent) {
  if (isDragging.current) {
    setPosition({
      x: e.data.global.x - offset.current.x,
      y: e.data.global.y - offset.current.y,
    });
  }
}
return (
  <WrappedComponent
    {...(props as T)}
    ref={containerRef}
    alpha={alpha}
    position={position}
    zIndex={zIndex}
    eventMode='static'
    cursor='pointer'
    pointerdown={onStart}
    pointerup={onEnd}
    pointerupoutside={onEnd}
    pointermove={onMove}
  />
);

}; }


Then you can use this new component to extend Pixi React components, e.g:

- src/App.tsx
```tsx
import { Sprite } from '@pixi/react';
import { withPixiDraggable } from './hocs/withPixiDraggable';

export const DraggableSprite = withPixiDraggable(Sprite);

export const App: React.FC = () => {
  return (
    <Stage>
      <DraggableSprite
        image="..."
        width={250}
        height={250}
      />
    </Stage>
  );
};

export default App;

Wondering if you can include HOCs like this from this project, any feedback is really appreciated! <3