Building Serverless React Forms Using React Hook Form & Getform.io

React-Hook-Form

$ npm install react-hook-form
import * as React from "react";
import { useForm } from "react-hook-form";
export default () => {
const { handleSubmit, register, watch, errors } = useForm();
const onSubmit = (data) => console.info(data); console.info(watch("firstName"));
console.info(watch("lastName"));
console.info(watch("age"));
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstName" ref={register({ required: true })} />
{errors.firstName && <span>First Name Is Required</span>}
<input name="lastName" ref={register({ required: true })} />
{errors.lastName && <span>Last Name Is Required</span>}
<input name="age" defaultValue="21" ref={register()} /> <input type="submit" />
</form>
);
};

Getform.io

import axios from "axios";
import * as React from "react";
import { useForm } from "react-hook-form";
export default () => {
const [serverState, setServerState] = useState({ submitting: false, status: null });
const handleServerResponse = (ok, msg, form) => {
setServerState({ submitting: false, status: { ok, msg } });
if (ok) {
// show success message
// handle success next steps
return;
}
// show failure message
// handle failure next steps
return;
};
const onSubmit = (data, e) => {
const formData = new FormData();
for (var field in data) {
formData.append(field, data[field]);
}
setServerState({ submitting: true }); // replace the url parameter with your own GetForm.io form id/url
axios({
method: "post",
url: "https://getform.io/f/11111111-aaaa-1111-aaaa-111111111111",
data: formData,
})
.then((r) => {
e.target.reset();
handleServerResponse(true, "Form Submitted", e);
})
.catch((r) => {
handleServerResponse(false, r.response.data.error, e);
});
};
const { handleSubmit, register, watch, errors } = useForm(); console.info(watch("firstName"));
console.info(watch("lastName"));
console.info(watch("age"));
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstName" ref={register({ required: true })} />
{errors.firstName && <span>First Name Is Required</span>}
<input name="lastName" ref={register({ required: true })} />
{errors.lastName && <span>Last Name Is Required</span>}
<input name="age" defaultValue="21" ref={register()} /> <input type="submit" />
</form>
);
};

Zapping GetForm.io To Mailchimp

Wrapping up

Experienced CTO, technical architect, board advisor & technical leader. I focus on building distributed applications & great teams.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store