Home > OS >  Trouble getting html element in react
Trouble getting html element in react

Time:09-06

I am trying to add an script to an element created by a react component. The idea is to draw some effects in a canvas of id="matrix" using the script.

I have successfully added the script to my index.html and I am trying to execute it. However, my document.getElementById("matrix") returns null.

List of things I tried to do:

  1. useEffect of this answer.
  2. Change import script to end of body tag.
  3. Change document.getElementById("matrix") to document.querySelector("#matrix")

My index.html body:

<body>
    <div id="root" ></div>
    <script async scr="../src/MatrixEffect/matrix.js"></script>
</body>

matrix.js (script):

window.onload = Init;

function Init() {
  const canvas = document.getElementById("matrix");
  /* const canvas = document.querySelector("#matrix"); */
  console.log(canvas); /*returns null */
  const context = canvas.getContext("2d");
}

MatrixComponent.js:


import styles from "./Matrix.module.css";

const MatrixComponent = () => {
  return (
    <div className={`${styles.container}`}>
      <canvas id="matrix" className={`${styles.canvas}`}></canvas>
    </div>
  );
};

export default MatrixComponent;

Error:

matrix.js:7 Uncaught TypeError: Cannot read properties of null (reading 'getContext') at Init (matrix.js:7:1)

CodePudding user response:

I got to make it work by using refs:

React functions:

export default function MatrixComponent() {
  const ref = useRef();

  useEffect(() => {
    if (ref.current) {
      const canvas = ref.current;

      
      console.log(canvas);
      const context = canvas.getContext("2d");
      /* rest of code */
    }
  }, []);

  return (
    <div className={`${styles.container}`}>
      <canvas ref={ref} className={`${styles.canvas}`} />
    </div>
  );
}

React classes:

import React from "react";

class MatrixComponent2 extends React.Component {
  constructor(props) {
    super(props);

    this.matrix = React.createRef();
  }

  componentDidMount() {
    this.context = this.matrix.current.getContext("2d");
    /*rest of code*/
  }

  render() {
    return <canvas ref={this.matrix} />;
  }
}
export default MatrixComponent2;
  • Related