Last active
March 5, 2020 11:46
-
-
Save kayode-adechinan/792d0ae405e55b6df2be31b006309473 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import {useFormik} from 'formik' | |
export default function Register(){ | |
function validate(values){ | |
const errors = {} | |
if(!values.firstName){ | |
errors.firstName = "Required" | |
} | |
if(!values.lastName){ | |
errors.lastName = "Required" | |
} | |
return errors; | |
} | |
const {handleSubmit, handleChange, values, errors} = useFormik({ | |
initialValues:{ | |
firstName:"", | |
lastName:"" | |
}, | |
validate, | |
onSubmit(values){ | |
console.log(values) | |
} | |
}) | |
return ( | |
<form onSubmit={handleSubmit}> | |
<input | |
name="firstName" | |
onChange={handleChange} | |
values={values.firstName} | |
/> | |
{errors.firstName? errors.firstName: null} | |
<input | |
name="lastName" | |
onChange={handleChange} | |
values={values.lastName} | |
/> | |
{errors.firstName? errors.firstName: null} | |
<button type="submit" >Submit</button> | |
</form> | |
) | |
} |
Author
kayode-adechinan
commented
Mar 5, 2020
import React, { Component } from "react";
import { Formik } from "formik";
import * as Yup from "yup";
const validationSchema = Yup.object({
firstName: Yup.string().required("Required"),
lastName: Yup.string().required("Required")
});
export default class App extends Component {
render() {
return (
<Formik
initialValues={{ firstName: "", lastName: "" }}
validationSchema={validationSchema}
onSubmit={values => {
console.log(values);
}}
>
{({ handleSubmit, handleChange, values, errors }) => (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={handleChange}
value={values.firstName}
name="firstName"
/>
{errors.firstName}
<input
type="text"
onChange={handleChange}
value={values.lastName}
name="lastName"
/>
{errors.lastName}
<button type="submit">Submit</button>
</form>
)}
</Formik>
);
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment