Skip to content

Instantly share code, notes, and snippets.

@chriskavanagh
Created January 2, 2020 04:05
Show Gist options
  • Save chriskavanagh/c4957a0a37e8c694a4d13827c847992a to your computer and use it in GitHub Desktop.
Save chriskavanagh/c4957a0a37e8c694a4d13827c847992a to your computer and use it in GitHub Desktop.
import React from "react";
import { Formik } from "formik";
import * as Yup from "yup";
//import Error from "./Error";
import styled from "styled-components";
const Form = styled.form`
width: 100%;
max-width: 600px;
margin: 25px auto;
.has-error {
border: 1px solid #f44336;
}
.input-row {
margin: 25px 0px;
}
label {
display: block;
padding-bottom: 5px;
font-size: 20px;
font-weight: bolder;
color: navy;
}
input {
width: 100%;
padding: 5px;
border-radius: 5px;
}
`;
const Button = styled.button`
background: gray;
color: white;
width: 30%;
border-radius: 5px;
font-size: 20px;
padding: 5px 0px;
border: 1px solid #607d8b;
cursor: pointer;
font-weight: bolder;
`;
// Yup Schema
const schema = Yup.object().shape({
name: Yup.string()
.min(5, "Name Must Be At Least 5 Characters")
.max(25, "Too Many Characters")
.required("Name Required"),
email: Yup.string()
.email("Please Enter a valid Email")
.required("Email Required")
});
const FormikForm = () => {
return (
<Formik
initialValues={{ name: "", email: "" }}
validationSchema={schema}
onSubmit={(values, { setSubmitting, resetForm }) => {
setSubmitting(true);
alert(JSON.stringify(values, null, 2));
resetForm();
setSubmitting(false);
}}
>
{({
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isSubmitting
}) => (
<Form onSubmit={handleSubmit}>
<div className="input-row">
<label htmlFor="name">Name</label>
<input
type="text"
name="name"
id="name"
placeholder="Enter Your Name"
onBlur={handleBlur}
onChange={handleChange}
value={values.name}
className={touched.name && errors.name ? "has-error" : null}
/>
{errors.name && touched.name ? <div>{errors.name}</div> : null}
</div>
<div className="input-row">
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
id="email"
placeholder="Enter Your Email"
onBlur={handleBlur}
onChange={handleChange}
value={values.email}
className={touched.email && errors.email ? "has-error" : null}
/>
{errors.email && touched.email ? <div>{errors.email}</div> : null}
</div>
<div className="input-row">
<Button disabled={isSubmitting} type="submit">
Submit
</Button>
</div>
</Form>
)}
</Formik>
);
};
export default FormikForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment