I have just started coding in React. I have a question related to handling form data. In some of the examples, the data is put in the component state:
this.state = {
username: '',
password: ''
}
One of my friends told me that data is not safe (all of the component state can be easily viewed with React developer tools) if I put all the form data in the component state.
I am really confused by this.
I have written below code. I have moved username and password out of the component.
let formFields = {
username: '',
password: ''
};
export default class LoginComponent extends React.Component {
constructor() {
super();
this.state = {
error: {
username: false,
password: false
}
};
}
render() {
return (
<div className="mp-form">
<form>
<div className="field-wrap">
<input type="text" placeholder="USERNAME" onChange={event => handleEvent.call(this, 'username', event.target.value)} />
<span style={{
display: this.state.error.username === true ? 'block' : 'none'
}}>Please enter UserName</span>
</div>
<div className="field-wrap">
<input type="password" placeholder="PASSWORD" onChange={event => handleEvent.call(this, 'password', event.target.value)} />
<span style={{
display: this.state.error.password === true ? 'block' : 'none'
}}>Please enter Password</span>
</div>
<div className="field-wrap">
<input type="button" value="Cancel" />
<input type="button" value="Create" />
</div>
</form>
<p>Don't have an account yet? Register here</p>
</div>
);
}
}
function handleEvent(type, value, context) {
if (type === 'username') {
formFields.username = value;
}
else if (type === 'password') {
formFields.password = value
}
console.log(type, value);
var userNameStatus = formFields.username.length === 0 ? true : false;
var passwordStatus = formFields.password.length === 0 ? true : false;
this.setState({
error: {
username: userNameStatus,
password: passwordStatus
}
});
}
What is the best practice for handling form data with validation?