I’m working on a project that integrates p5.js and React. My project consists of App.js and two child components: View1.js and View2.js. I want to pass information from View1 to View2 and have that changing information reflected in the sketch of View 2. My problem is that although I can pass data from View 1 to View 2, I don’t know how to update the sketch with the new value.
I think part of the problem might be caused by the fact that the sketch within the View 2 component is in instance mode, so once it’s initialized, it doesn’t change. Essentially, I’m looking for a way to reinitialize/refresh the sketch inside a component every time one of the component’s props changes in value so that the sketch is using the most recent value. I know p5-react-wrapper does have a way of dealing with this problem, but ideally, I'd like to do this with just the p5 library.
Does anyone know how to do that? I've included an example of what I want to do below (although it's a bit more complicated than this with my actual project).
App.js
import React, { useState } from 'react';
import View1 from "./components/View1.js";
import View2 from './components/View2.js';
function App() {
const [data, setData] = useState(0);
const firstViewToParent = (num) => {setData(num);}
return (
<div className="App">
<View1
firstViewToParent={firstViewToParent}
/>
<View2
dataFromSibling={data}
/>
</div>
);
}
export default App;
View1.js
import React, { useEffect } from "react";
import p5 from 'p5';
const View1 = props => {
const Sketch = (p) => {
p.setup = () => {
p.createCanvas(400, 400);
}
p.draw = () => {
p.background(0);
}
p.mouseClicked = () => {
// Passing information from the child up to the parent
props.firstViewToParent(p.mouseX);
}
}
useEffect(() => {
new p5(Sketch);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<></>
);
}
export default View1;
View2.js
import React, { useEffect } from "react";
import p5 from 'p5';
const View2 = props => {
const Sketch = (p) => {
p.setup = () => {
p.createCanvas(400, 400);
}
p.draw = () => {
p.background(255, 0, 0);
// Want to be able to access updated information from sibling
// component inside the sketch
p.print(props.dataFromSibling);
}
}
useEffect(() => {
new p5(Sketch);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<></>
);
}
export default View2;