'REACT application does not work after the page is refreshed with F5
I am learning React. In the App.js file, I have this simple component.
const p = document.getElementsByTagName("p")[0];
p.innerHTML = "Created with Javascript";
function App() {
return <p>Created with JSX</p>;
}
export default App;
As I expected, this is the result in my Browser.
Created with Javascript
But when I refresh the page with F5, the page is blank and I get this bug in the console.
>Uncaught TypeError: Cannot set properties of undefined (setting 'innerHTML')
>at Module../src/App.js (bundle.js:22:13)
>at Module.options.factory (bundle.js:41603:31)
>at __webpack_require__ (bundle.js:41075:33)
>at fn (bundle.js:41274:21)
>at Module../src/index.js (bundle.js:84:62)
>at Module.options.factory (bundle.js:41603:31)
>at __webpack_require__ (bundle.js:41075:33)
>at bundle.js:42178:37
>at bundle.js:42180:12
Why is this happening? I expected the same result after refreshing the page with F5.
Solution 1:[1]
This is happening, because p is undefined.
As long as nothing rendered on the page document.getElementsByTagName("p")[0]; will not be able to select anything.
You have to wait until rendering finishes and then select the html element.
You could use a useLayoutEffect for that, or you could rewrite your code to anticipate the usage of react with a ref from useRef. But for that we will need to know your use case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | henk |
