Using React with p5.js

(Eric Ettlin) #1

My high school kids have been writing p5.js programs. We are now using ReactJS. Will React allow us to create a canvas element that will run our p5.js code?

(Ivan Malyugin) #2

React is built around handling all the html changes in render method by built-in means. Using an external library that forces changes to dom is not exactly great idea. But it doesn’t seem impossible.

You may create a p5wrapper component and launch p5 in instance mode (, like that:

class P5Wrapper extends React.Component {
  componentDidMount() {
    this.canvas = new p5(sketch, this.refs.wrapper)
  componentWillReceiveProps(props, newprops) {
    if( this.canvas.myCustomRedrawAccordingToNewPropsHandler ) {
  render() {
    return <div ref="wrapper"></div>

Since render method here is props independant, react will never fire redrawing (shadowDom will always stay unchanged), keeping all p5 contents untouched - aka an isolated p5 system within React component.

And to break that isolation you can create myCustomRedrawAccordingToNewPropsHandler method within your sketch, it will send signals from react down to sketch, redrawing it depending on changes in react structure.

I would create one React Wrapper that receives p5 sketch as one of the props, this way you would be able to create multiple instances reusing a single react component, passing down different sketches.

Never tested any of this, nor even used p5js, but it seems about right.

(Eric Ettlin) #3

Thank you–I’ll give this a try.

(Nero Cor) #4

Hello Eric and Ivan,

I build a React Component out of this.
Just a first draft but its working :slight_smile:

So if you want to contribute contact me.

You find the Component here:

(wanbinkimoon) #5

Hi, i’m trying to use your component but I can’t make it work because it doesn’t seems to recognize p5 costants as


(Sjors Van Heuveln) #6

You have to use p.CENTER.

(Sjors Van Heuveln) #7

How would you for example send a function down as props into the sketch. For example I would like to send down a Redux action that can manipulate my state in the store.