Skip to content

Instantly share code, notes, and snippets.

@marcusstenbeck
Last active October 11, 2018 17:07
Show Gist options
  • Save marcusstenbeck/d05ea56c8ccefceb7a89b2db48673c01 to your computer and use it in GitHub Desktop.
Save marcusstenbeck/d05ea56c8ccefceb7a89b2db48673c01 to your computer and use it in GitHub Desktop.
React Form handler using render props
// Live example: https://codesandbox.io/s/llo5y66pxq
import React from 'react';
import ReactDOM from 'react-dom';
import Form from './Form';
const App = () => (
<Form onSubmit={props => alert(JSON.stringify(props, 0, 2))}>
{({ onChange }) => (
<React.Fragment>
<input
type="text"
name="name"
onChange={onChange}
placeholder="Name"
/>
<input
type="text"
name="message"
onChange={onChange}
placeholder="Message"
/>
<button type="submit">
Alert values
</button>
</React.Fragment>
)}
</Form>
);
const rootElement = document.createElement('div');
document.appendChild(rootElement);
ReactDOM.render(<App />, rootElement);
import React from 'react';
import T from 'prop-types';
class Form extends React.Component {
static propTypes = {
onSubmit: T.func.isRequired,
children: T.func.isRequired,
};
constructor(props, ...rest) {
super(props, ...rest);
this.state = { input: props.values || {} };
}
handleChange = evt => {
evt.preventDefault();
const { id, name, value } = evt.target;
this.setState(({ input }) => ({
input: { ...input, [name || id]: value },
}));
};
handleSubmit = evt => {
evt.preventDefault();
this.props.onSubmit({ values: this.state.input });
};
render() {
const { children, onSubmit, ...rest } = this.props;
return (
<form onSubmit={this.handleSubmit} {...rest}>
{children({ onChange: this.handleChange, ...this.state, ...rest })}
</form>
);
}
}
export default Form;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment