Skip to content

Instantly share code, notes, and snippets.

@yomeshgupta
Created August 17, 2018 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yomeshgupta/0899459ec3cc357aa899a41f1df035ea to your computer and use it in GitHub Desktop.
Save yomeshgupta/0899459ec3cc357aa899a41f1df035ea to your computer and use it in GitHub Desktop.
An example of form handling using React and Redux
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { updateUser } from '../actions/userActions';
class Form extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
handleSubmit(name = this.props.name, email = this.props.email, password = false) {
if (!name || !name.trim().length || (!email || !email.trim().length) || (password && !password.trim().length)) {
this.setState({
erorr: true,
message: 'Invalid data'
});
return;
}
this.setState(
{
error: false,
message: ''
},
() => {
this.props.updateUser({
name,
email,
password
});
}
);
}
render() {
return (
<form
onSubmit={e => {
e.preventDefault();
this.handleSubmit({
name: this.state.name,
email: this.state.email,
password: this.state.password
});
}}
>
<input
type="text"
value={this.state.name}
defaultValue={this.props.name}
name="name"
onChange={this.handleChange}
/>
<input
type="email"
value={this.state.email}
defaultValue={this.props.email}
name="email"
onChange={this.handleChange}
/>
<input type="password" value={this.state.password || ''} name="password" onChange={this.handleChange} />
<input type="submit" value="Save" />
</form>
);
}
}
const mapStateToProps = (state, ownProps) => ({
name: state.user.name,
email: state.user.email,
password: state.user.password,
...ownProps.props
}),
mapDispatchToProps = dispatch => ({
updateUser: params => dispatch(updateUser(params))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Form);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment