Last active
May 1, 2020 21:10
-
-
Save yawaramin/c0c93003dcd2284f9346d2f58c8ac490 to your computer and use it in GitHub Desktop.
ReasonML/BuckleScript bindings for Formik
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
[@bs.module "formik"] | |
[@react.component] | |
external make: ( | |
~initialValues: Js.t('a), | |
~validate: (. Js.t('a)) => Js.Dict.t(string), | |
~onSubmit: (. Js.t('a), {. "setSubmitting": [@bs.meth] bool => unit }) => unit, | |
~children: (. {. "isSubmitting": bool }) => React.element, | |
) => React.element = "Formik"; | |
module Form = { | |
[@bs.module "formik"] | |
[@react.component] | |
external make: (~children: React.element) => React.element = "Form"; | |
}; | |
module Field = { | |
[@bs.module "formik"] | |
[@react.component] | |
external make: (~_type: string, ~name: string) => React.element = "Field"; | |
}; | |
module ErrorMessage = { | |
[@bs.module "formik"] | |
[@react.component] | |
external make: (~name: string, ~component: string) => React.element = "ErrorMessage"; | |
}; |
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
let initialValues = { "email": "", "password": "" }; | |
let validate = (. values) => { | |
let errors = Js.Dict.empty(); | |
if (values##email == "") | |
Js.Dict.set(errors, "email", "Required") | |
else if (!Js.Re.test_([%re "/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i"], values##email)) | |
Js.Dict.set(errors, "email", "Invalid email address"); | |
errors; | |
}; | |
module F = Formik; | |
let make() = | |
<F | |
initialValues | |
validate | |
onSubmit={(. values, setters) => | |
ignore(Js.Global.setTimeout( | |
() => { | |
Js.log(values); | |
setters##setSubmitting(false); | |
}, | |
400))}> | |
{(. props) => | |
<F.Form> | |
<F.Field _type="email" name="email" /> | |
<F.ErrorMessage name="email" component="div" /> | |
<F.Field _type="password" name="password" /> | |
<F.ErrorMessage name="password" component="div" /> | |
<button type_="submit" disabled={props##isSubmitting}> | |
"Submit"->React.string | |
</button> | |
</F.Form>} | |
</F>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment