Actually I am trying to set a
elements innerHTML to some value from local storage ,It shows the value for the first time but whenever I trying to reload the page it shows error like the screenshot below!
here is the code-
const getName = window.localStorage.getItem("name");
if(getName.charAt(0) == "M"){
document.getElementById("myidname").innerHTML = "some message";
}else{
console.log("error")
}
<p id='myidname'></p>
I tried to wrap statements into a method then using that method inside the
element but still showing same error.
2
Answers
The error you’re encountering likely stems from trying to manipulate the DOM directly in React before the component has fully mounted, which can lead to accessing elements that do not yet exist. Additionally, when you reload the page, if the localStorage item "name" is not set or is empty, trying to call .charAt(0) on null or undefined will throw an error.
React recommends a more declarative approach to DOM manipulation, favoring state and props over direct manipulation. To achieve your goal while adhering to React’s best practices, you can use component state and the useEffect hook to read from localStorage and conditionally render content based on that value.
Here’s a revised approach that avoids direct DOM manipulation and error:
To avoid this issue, you should check if getName is not null or undefined before trying to access its properties. You can follow code:
By following these few steps, you ensure that you handle cases where the local storage value may not exist or may not have the expected format.