Skip to content

Instantly share code, notes, and snippets.

@WoonHaKim
Created October 2, 2018 12:30
Show Gist options
  • Save WoonHaKim/0911c925701f188d1c1f78e32e35d478 to your computer and use it in GitHub Desktop.
Save WoonHaKim/0911c925701f188d1c1f78e32e35d478 to your computer and use it in GitHub Desktop.
Connecting p5js and React js
// Uses dynamic component loading feature of nextjs
import dynamic from 'next/dynamic';
import sketch from './BGSketch'; // Sketch to load dynamically
import css from '../styles.less'
const P5DynamicLoader = dynamic(import('./P5Wrapper'), {
ssr: false,
loading: () => <div className={css.backgroundCanvas}>Loading Background...</div>,
});
export default () => <div className={css.backgroundCanvas}><P5DynamicLoader sketch = {sketch}/></div>
//requires p5 library from npm
import React, { Component } from 'react';
import p5 from 'p5';
export default class P5Wrapper extends React.Component {
componentDidMount() {
this.canvas = new p5(this.props.sketch, this.wrapper);
if( this.canvas.myCustomRedrawAccordingToNewPropsHandler ) {
this.canvas.myCustomRedrawAccordingToNewPropsHandler(this.props)
}
}
componentWillReceiveProps(newprops) {
if(this.props.sketch !== newprops.sketch){
this.canvas.remove()
this.canvas = new p5(newprops.sketch, this.wrapper)
}
if( this.canvas.myCustomRedrawAccordingToNewPropsHandler ) {
this.canvas.myCustomRedrawAccordingToNewPropsHandler(newprops)
}
}
componentWillUnmount() {
this.canvas.remove()
}
render() {
return <div ref={wrapper => this.wrapper = wrapper}></div>
}
}
@COULY-GALLO-01
Copy link

very nice, i understand

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment