\nso you might want to run that after the component gets mounted.
\nYou can use useEffect for that
\n","author":{"@type":"Person","name":"Akash NO"},"upvoteCount":2}}}Reputation: 27
I am working on a React project, I got some syntax error like this TypeError: Cannot read property 'id' of null. According to me my code is ok but I don't know why this error is showing so someone please help me to resolve this error
This is my code
import React, { useEffect, useRef } from 'react';
import './App.css';
const App = () => {
const initialMessage = useRef(null)
const initialMsg = initialMessage.current.id
console.log(initialMsg, 'One')
return (
<>
<div id="screen-initial">
<h1 id="msg" ref={initialMessage}>Loading...</h1>
<progress id="load-progress" value="0" max="100"></progress>
</div>
<div id="screen-start" class="hidden">
<a href="#" id="start-scan">Start scan</a>
</div>
<div id="screen-scanning" class="hidden">
<video id="camera-feed" playsinline></video>
<canvas id="camera-feedback"></canvas>
<p id="camera-guides">
Point the camera towards front side of a document.
</p>
</div>
</>
)
}
export default App
Upvotes: 0
Views: 1229
Reputation: 316
Because the
const initialMsg = initialMessage.current.id
is running before the componenet gets mounted
so you might want to run that after the component gets mounted.
You can use useEffect for that
Upvotes: 2
Reputation: 59
Before the initial render, the intialMessageis ref is not defined.
You can fix it as follows by putting it inside useEffect as that will run only after the first render:
import React, { useEffect, useRef } from 'react';
import './App.css';
const App = () => {
const initialMessage = useRef(null)
// Use it inside useffect
React.useEffect(()=>{
const initialMsg = initialMessage?.current?.id //<== HERE
console.log(initialMsg, 'One')
},[])
return (
<>
<div id="screen-initial">
<h1 id="msg" ref={initialMessage}>Loading...</h1>
<progress id="load-progress" value="0" max="100"></progress>
</div>
<div id="screen-start" class="hidden">
<a href="#" id="start-scan">Start scan</a>
</div>
<div id="screen-scanning" class="hidden">
<video id="camera-feed" playsinline></video>
<canvas id="camera-feedback"></canvas>
<p id="camera-guides">
Point the camera towards front side of a document.
</p>
</div>
</>
)
}
export default App
Upvotes: 1