I am trying to create the matrix rain effect as my background in react. I have created a matrix rain rain function that I use to wrap all of my other components with. But I get an error saying 'TypeError: canvas.getContext is not a function'. I am trying to follow the template mentioned on this site https://medium.com/@pdx.lucasm/canvas-with-react-js-32e133c05258 What am I doing wrong here? why is it not working?
MatrixRain.js file
import './MatrixRain.css';
import React, {useEffect, useContext, useRef, useState, useCallback} from 'react';
const MatrixRain = ( props ) => {
const canvasRef = useRef(null)
useEffect(() => {
const canvas = canvasRef.current;
const context = canvas.getContext('2d'); //this line is giving me an error
}, [])
return (
<div className='matrix-rain' ref={canvasRef}>
{props.children}
</div>
)
};
export default MatrixRain
App.js file
import React, { useState, useReducer, createContext, useContext } from 'react';
import PostList from './components/PostList/PostList.js';
import Title from './containers/Title/Title.js';
import Pagination from './components/Pagination/Pagination.js';
import Navbar from './containers/Navbar/Navbar.js';
import Button from './components/Button/Button.js';
import Store from './store/Store.js';
import MatrixRain from './containers/MatrixRain/MatrixRain'
import {
BrowserRouter as Router,
Routes,
Route,
Link,
Outlet,
useParams
} from 'react-router-dom';
const App = () => {
return (
<div>
<Store>
<MatrixRain>
<Button />
<Title />
<Navbar />
<PostList />
<Pagination />
</MatrixRain>
</Store>
</div>
);
}
export default App;
Nevermind, I found out what the problem was, all I had to do was change
<div className='matrix-rain' ref={canvasRef}>
{props.children}
</div>
to
<canvas className='matrix-rain' ref={canvasRef}>
{props.children}
</canvas>
and that did the trick for me