Skip to content
Advertisement

Passing value from p5 sketch to React (with react-p5-wrapper)

I have a p5 webcam video prediction system working right now. Currently, I’m trying to plug this into a React app to create a fuller web app.

My problem is, the prediction is now only made in my p5 sketch, I want the prediction value to be passed into React’s App.js for further constructions. Is there any method of doing so?

I’m using react-p5-wrapper btw.

Here’s the sketch.js:

JavaScript

And my App.js currently looks like this:

JavaScript

Any help appreciated!

Advertisement

Answer

I gave this a go and came up with a solution. It isn’t very elegant but it should do. I made a very simple test project in sketch.js where I try to illustrate two ways accessing the infromation. The things to note are the timesClicked variable and the updateWithProps function.

JavaScript

timesClicked is a variable that can be imported and counts the times the mouse has been clicked. It can be modified from inside the sketch scope and imported from other files.

updateWithProps is a function called from the react-p5-wrapper library whenever the component receives props and can be defined inside the sketch.

With this, your App.js file could be modified like so:

JavaScript

When running, every time there is a click, the sketch will execute the getCoords() function in the App.js file and, alternatively, every time the space bar is pressed the timesClicked variable will be accessed from the App.js file. I think you can modify this in order to “send” or “read” the prediction value.

Edited as per Daniel’s answer

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement