How to use React with p5.js

user11114318 picture user11114318 · Feb 25, 2019 · Viewed 10.2k times · Source

I really like p5.js and react.js so i wondered how to combine these two together, and i was unable to do it so I need your help. I cant really provide you with some code samples because I have no clue how to start.

So what I want to do : 1. create-react-app 2.render a canvas using p5.js (i dont need the p5.dom and p5.sound)

Answer

Julian picture Julian · Feb 27, 2019

First thing that needs to be done is install the create-react-app tool. Once it's up and running the p5.js and the react-p5-wrapper packages can be included; assuming a package manager like npm is being used, this can be done by executing npm install p5 react-p5-wrapper with whatever flags are considered necessary.

The react-p5-wrapper is a wrapper component that receives a reference (instance mode) to the sketch and uses some of the react component "lifecycle methods" to manipulate it accordingly, mainly by executing a method called myCustomRedrawAccordingToNewPropsHandler(props) that needs to be defined within said sketch.

To give it a try and see it running, the contents of the App.js file could be modified like this:

import React, { Component } from 'react';
import P5Wrapper from 'react-p5-wrapper';
import sketch from './sketches/sketch';
import './App.css';

class App extends Component {
  constructor(){
    super();
    this.state = {color:[Math.random()*255, Math.random()*255, Math.random()*255]};
    this.randomColor = this.randomColor.bind(this);
  }

  randomColor(){
    this.setState({color:[Math.random()*255, Math.random()*255, Math.random()*255]}
    )
  }

  render() {
    return (
      <div>
        <button onClick={this.randomColor}>Random Color</button>
        <P5Wrapper sketch={sketch} color={this.state.color}></P5Wrapper>
      </div>
    );
  }
}

export default App;

Where sketch is imported from sketch.js which is located in another folder, in this case called sketches:

export default function sketch(p){
    let canvas;

    p.setup = () => {
      canvas = p.createCanvas(300, 200);
      p.noStroke();
    }

    p.draw = () => {
      p.background('orangered');
      p.ellipse(150, 100, 100, 100);
    }

    p.myCustomRedrawAccordingToNewPropsHandler = (newProps) => {
      if(canvas) //Make sure the canvas has been created
        p.fill(newProps.color);
    }
}

If everything is working, a button and a sketch should be on screen and every time the button is pressed the circle in the sketch changes colors randomly.

It should be noted that the myCustomRedrawAccordingToNewPropsHandler function is called in the componentDidMount and the componentWillReceiveProps "lifecycle methods" of the wrapper, the latter being currently classified as unsafe.