I am trying to embed a p5js sketch in a React project. I am using react-script-tag to embed the .js file which contains the p5js sketch and I am using react-router-dom to manage the routes to the webpages. I have managed to get the p5js sketch displaying properly, however I am facing the following issue:
The ScriptTag referencing the p5js sketch is located within within the Route to '/p5js'.
<Route path="/p5js" element={<p5js />}/>
The p5js sketch only loads after I've refreshed the browser on that page, 'localhost:3000/p5js'. Once it loads, it remains on the screen even after I go to back to another page, say
<Route path="/home" element={<Home />}/>
How I can have the p5js sketch appear automatically when navigating to the p5js page? And how can I have the sketch disappear when navigating to new pages, such as the 'Home' page?
Here is my code:
App.js
import { BrowserRouter, Routes, Route } from "react-router-dom";
import "./App.css";
import Navbar from "./components/Navbar";
import Home from "./pages/Home";
import SQL from "./pages/SQL";
import SuperCollider from "./pages/SuperCollider";
import p5js from "./pages/p5js";
function App() {
return (
<>
<BrowserRouter>
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/sql" element={<SQL />} />
<Route path="/sc" element={<SuperCollider />} />
<Route path="/p5js" element={<p5js />} />
</Routes>
</BrowserRouter>
</>
);
};
export default App;
p5js.js
import React from 'react';
import ScriptTag from 'react-script-tag';
const p5js = () =>{
return (
<div className="p5js">
<ScriptTag type="text/javascript" src="sketch2.js" />
</div>
);
}
export default p5js;
I use react-p5-wrapper to use p5 as a component and have had similar issues with the p5 instance hanging around, consuming touch events and such.
I've found it useful to use p5's remove() function. Listen for a location change then call remove as needed.
Haven't had any issue with p5 not appearing / running when it's wrapper component is rendered.