Full development example of props and state
import React, { Component } from 'react';
export default class FormDataComponent extends Component {
userData;
constructor(props) {
super(props);
this.onChangeName = this.onChangeName.bind(this);
this.onChangeEmail = this.onChangeEmail.bind(this);
this.onChangePhone = this.onChangePhone.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
name: '',
email: '',
phone: ''
}
}
// Form Events
onChangeName(e) {
this.setState({ name: e.target.value })
}
onChangeEmail(e) {
this.setState({ email: e.target.value })
}
onChangePhone(e) {
this.setState({ phone: e.target.value })
}
onSubmit(e) {
e.preventDefault()
this.setState({
name: '',
email: '',
phone: ''
})
}
// React Life Cycle
componentDidMount() {
this.userData = JSON.parse(localStorage.getItem('user'));
if (localStorage.getItem('user')) {
this.setState({
name: this.userData.name,
email: this.userData.email,
phone: this.userData.phone
})
} else {
this.setState({
name: '',
email: '',
phone: ''
})
}
}
componentWillUpdate(nextProps, nextState) {
localStorage.setItem('user', JSON.stringify(nextState));
}
render() {
return (
)
}
}