Search code examples
reactjsreduxcreate-react-appphaser-framework

How to integrate Phaser into React


I've got a React application created with create-react-app and I'm trying to integrate Phaser 3 as well. I followed this guide to get started. I've got the canvas rendering the text but loading images in the preload does not seem to be working. I get the default failed to load texture image displayed.

import ExampleScene from "./scenes/ExampleScene";

import * as React from "react";

export default class Game extends React.Component {
  componentDidMount() {
    const config = {
      type: Phaser.AUTO,
      parent: "phaser-example",
      width: 800,
      height: 600,
      scene: [ExampleScene]
    };

    new Phaser.Game(config);
  }

  shouldComponentUpdate() {
    return false;
  }

  render() {
    return <div id="phaser-game" />;
  }
}

ExampleScene:

import Phaser from "phaser";

export default class ExampleScene extends Phaser.Scene {
  preload() {
    this.load.image("logo", "assets/logo.png");
  }
  create() {
    const text = this.add.text(250, 250, "Phaser", {
      backgroundColor: "white",
      color: "blue",
      fontSize: 48
    });

    text.setInteractive({ useHandCursor: true });
    this.add.image(400, 300, "logo");

    text.on("pointerup", () => {
      console.log("Hello!");
      //store.dispatch({ type: ACTION_TYPE });
    });
  }
}

The idea is to create a visualization with flowers growing based on a simple gene engine. So Phaser would get instructions from the Store about the current state.

I'm guess this has something to do with the way Phaser loads and there's a conflict with how React updates. I'm preventing the component from updating as I only need the game to receive instructions by listening to the store

I've already looked at this SO answer and the accompanying wrapper, but it is outdated.

How can I get Phaser to load images when in a Create-React-App?

CodeSandbox: https://codesandbox.io/s/github/nodes777/react-punnett/tree/phaser-game Repo: https://github.com/nodes777/react-punnett/tree/phaser-game


Solution

  • EDIT: There is now an official React and Phaser integration: https://github.com/phaserjs/template-react

    I started from scratch and created my own boilerplate from the phaser 3 template. I wrote about the specific steps to add React to the Phaser 3 template here.

    It seems like you could eject from Create-React-App and add in Phaser 3 from there, but the warnings not to eject turned me away from that solution.