<div id="index"></div>
//based on https://www.youtube.com/watch?v=oiNtnehlaTo
// and https://reactjs.org/docs/forms.html#handling-multiple-inputs
class BabyFormik extends React.Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.handleBlur = this.handleBlur.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.state = {
values: this.props.initialValues || {},
touched: {},
errors: {}
}
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
//setState modifies the state for the keys that are supplied.
//if a key is not supplied, that state is left unmodified
this.setState(prevState => ({
values: {
...prevState.values,
[name]: value
}
}))
}
handleBlur(event) {
const target = event.target
const name = target.name
this.setState(prevState => ({
touched: {
...prevState.touched,
[name]: true
}
}))
}
handleSubmit(event) {
event.preventDefault()
//add validation here
//set `isSubmitting` to true here as well
this.props.onSubmit(this.state.values)
}
render() {
//pass state and callbacks to child as parameters
return React.cloneElement(this.props.children, {
state: this.state,
handleChange: this.handleChange,
handleBlur: this.handleBlur,
handleSubmit: this.handleSubmit
})
}
}
const ReservationForm = ({state, handleChange, handleBlur, handleSubmit}) => {
return <form onSubmit={handleSubmit}>
<label>
Is going:
<input
name="isGoing"
type="checkbox"
checked={state.values.isGoing}
onChange={handleChange}
onBlur={handleBlur}/>
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests"
type="number"
value={state.values.numberOfGuests}
onChange={handleChange}
onBlur={handleBlur}/>
</label>
<button>Submit</button>
<pre>{JSON.stringify(state)}</pre>
</form>
}
const ReservationFormWithBabyFormik = props => {
const initialValues = {
isGoing: true,
numberOfGuests: 2,
}
const onSubmit = values => alert(JSON.stringify(values))
return <BabyFormik initialValues={initialValues} onSubmit={onSubmit}>
<ReservationForm/>
</BabyFormik>
}
ReactDOM.render(<ReservationFormWithBabyFormik/>, document.getElementById('index'));
View Compiled
This Pen doesn't use any external CSS resources.