I have a question for you... On my react app, I have a <input></input>
but I would like the user to be able to keep his message thanks to the local storage.
class Profil extends Component {
message() {
if (localStorage != 'undefined'){
document.getElementById('message').value = localStorage.getItem('message');
}
else {
alert("localStorage is not supported");
}
}
render() {
return (
<div>
<input name="message" onChange={() => this.message()}></input>
</div>
);
}}
With that, when I put a letter, I have directly an error message :
TypeError: localStorage.getItem(...) is null
and this line is false :
document.getElementById('message').value = localStorage.getItem('message');
What do I have to do ?
Instead of manipulating the DOM manually, you could keep the message in state and update the localStorage value on every change, and also read the value from localStorage when the component is created.
Example
class Profile extends React.Component {
constructor() {
super();
this.state = {
message: localStorage.getItem("message") || ""
};
}
onChange = event => {
const message = event.target.value;
localStorage.setItem("message", message);
this.setState({ message });
};
render() {
return <input value={this.state.message} onChange={this.onChange} />;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With