Skip to content

Instantly share code, notes, and snippets.

@alsma
Last active October 26, 2016 15:03
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 alsma/f837a0f9942fa2822f5f2e4ffb35b486 to your computer and use it in GitHub Desktop.
Save alsma/f837a0f9942fa2822f5f2e4ffb35b486 to your computer and use it in GitHub Desktop.
import React, { Component, PropTypes } from 'react';
class FormClass extends Component {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
setRef: PropTypes.func,
};
constructor(props) {
super(props);
this.state = this.prepareState();
}
componentWillMount() {
this.props.setRef && this.props.setRef(this);
}
componentWillUnmount() {
this.props.setRef && this.props.setRef(null);
}
prepareState() {
return { field1: '', field2: '' }
}
reset() {
this.setState(this.prepareState());
}
handleChange(id, value) {
this.setState({ [id]: value });
}
handleSubmit() {
this.props.onSubmit(this.state);
}
render() {
return (
<form onSubmit={::this.handleSubmit}>
<input id="field1" value={this.state.field1} onChange={(e) => this.handleChange(e.target.id, e.target.value)}/>
<input id="field2" value={this.state.field2} onChange={(e) => this.handleChange(e.target.id, e.target.value)}/>
</form>
);
}
}
const CustomForm = compose(hoc1(), hoc2())(FormClass);
class Parent extends Component {
handleFormSubmit(data) {
$.post(...).then(this.formRef.reset());
}
render() {
return <Form onSubmit={::this.handleFormSubmit} setRef={ref => this.formRef = ref }/>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment