I'm currently working on a site with react that is going to use anime.js for some animations. I want to have code that selects a canvas element and can make changes to it.
var canvasEl = document.querySelector('.clickpad');
var ctx = canvasEl.getContext('2d');
...
However, I'm not sure how I could implement this in React. I've read some stuff online about React.createref, but I'm still unsure about how I could use in this situation.
Here is the HTML within my react component:
const Practice = () => (
<div className="info">
<TitleBar />
<div className="box">
<h3>Test</h3>
</div>
<canvas className="clickpad"></canvas>
</div>
);
Any help would be greatly appreciated!
For a functional component, you'd use the useRef hook:
const Practice = () => {
const canvasRef = React.useRef();
React.useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext("2d");
// use this to draw something on every redraw of the component
});
return (
<div className="info">
<TitleBar />
<div className="box">
<h3>Test</h3>
</div>
<canvas className="clickpad" ref={canvasRef}></canvas>
</div>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With