简体   繁体   中英

Trouble getting html element in react

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" class="has-navbar-fixed-top"></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)

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM