Skip to content

Instantly share code, notes, and snippets.

@benjaminparnell
Created September 11, 2018 20:23
Show Gist options
  • Save benjaminparnell/20198e134aaa254224ad8bbbfd595e45 to your computer and use it in GitHub Desktop.
Save benjaminparnell/20198e134aaa254224ad8bbbfd595e45 to your computer and use it in GitHub Desktop.
// This example allows:
//
// `age` to be zero as a valid initial value, or any other number. If its undefined the input
// will be empty instead of zero.
//
// `value` to be undefined, leaving please select as selected, or preset to any other number
// including zero.
//
// It also makes use of yup's schema.cast (post submit) to get around select values
// coming out as strings. This is better than manually having to catch these cases
// yourself.
import * as React from "react";
import { render } from "react-dom";
import { Formik, Form, Field } from "formik";
import * as yup from 'yup';
function isNull(value: any) {
return value === undefined || value === null;
}
type Props = {
age?: number;
value?: number;
};
const validationSchema = yup.object().shape({
age: yup.number().required(),
value: yup.number().oneOf([1,2,3]).required()
})
class App extends React.Component<Props> {
onSubmit(values) {
// selects always return things as strings. You can use schema.cast to
// attempt to cast the object to its proper types if they don't match, like this
console.log(validationSchema.cast(values))
}
render() {
const { age, value } = this.props;
return (
<Formik
validationSchema={validationSchema}
onSubmit={this.onSubmit}
initialValues={{
age: isNull(age) ? "" : age,
value: isNull(value) ? "" : value
}}
render={({ isValid }) => (
<Form>
<div>
<label>Age</label>
<Field name="age" type="number" />
</div>
<div>
<label>Value</label>
<Field name="value" component="select">
<option value="">Please select one</option>
{[1, 2, 3].map(val => (
<option key={val} value={val}>
{val}
</option>
))}
</Field>
</div>
<button type="submit" disabled={!isValid}>Submit</button>
</Form>
)}
/>
);
}
}
render(<App age={0} />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment