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:
- useEffect of this answer.
- Change import script to end of body tag.
- Change
document.getElementById("matrix")
todocument.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)