javascriptreactjsreact-dompixi.js

React 18 and Pixijs 7


I am currently trying to use Pixi 7 with a react-dom 18 frontend. I need to add / remove multiple canvases dynamically within a single page application. I have not figured out a way to even get "normal" pixi.js to work.

I do not want to build with the pixi/react module (as this is only a subset of pixi). What I need is the full Pixi. Is there a way to do this? Here is my code:

import React, { Component } from "react";
import { Application, Sprite, Texture, Container } from 'pixi.js';


class Unit extends Component {
    render() {
        return (
            <div id="stage"></div>
        );
    }

        componentDidMount() {
            const app = new Application({
                view: document.getElementById("stage"),
                resolution: window.devicePixelRatio || 1,
                autoDensity: true,
                backgroundColor: 0x6495ed,
                width: 640,
                height: 480
            });

            const conty = new Container();
            conty.x = 200;
            conty.y = 0;
            app.stage.addChild(conty);
            
            const clampy = Sprite.from("clampy.png");
            clampy.x = 100;
            clampy.y = 100;
            conty.addChild(clampy);

        }
}




export default Unit;


Solution

  • Here is how I solved it as of now for react 18 and pixi.js 8, without any dependencies on react/pixi.

    It works on StrictMode, whatever you want.

    import { useCallback, useEffect, useRef } from 'react'
    import { Application } from 'pixi.js';
    
    export default function PixiApp({ width, height }) {
      const canvasRef = useRef(null)
      const init = useCallback(async() => {
        const canvas = canvasRef.current
        const app = new Application()
        await app.init({ width, height, canvas })
        return app  
      }, [])
    
      useEffect(() => {
        const app = init()
        return async() => (await app).stop()
      }, [init])
    
      return <canvas ref={canvasRef} />;
    }