Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I use instead of document.queryselector() when using React?

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!

like image 531
mark Avatar asked Apr 15 '26 00:04

mark


1 Answers

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>
  );
};
like image 115
AKX Avatar answered Apr 16 '26 12:04

AKX