Skip to content

Instantly share code, notes, and snippets.

@nicolasleal570
Last active September 10, 2020 19:48
Show Gist options
  • Save nicolasleal570/c805a8ccd142eef1dea55a2894773f45 to your computer and use it in GitHub Desktop.
Save nicolasleal570/c805a8ccd142eef1dea55a2894773f45 to your computer and use it in GitHub Desktop.
Multi Step Form - Medium Tutorial
import React from "react";
import { useForm, useStep } from "react-hooks-helper";
import { AuthInfo, BasicInfo, ContactInfo, FormReview, ProgressBar } from "./";
// Describe the keys to know what steps the form will have
const steps: Array<string> = ["auth", "basicInfo", "contact", "review"];
// Type to know what inputs the form will have
export interface FormData {
email: string;
username: string;
password: string;
name: string;
lastName: string;
phone: string;
address: string;
}
export default function () {
const [formData, setForm] = useForm<FormData>({
email: "",
username: "",
password: "",
name: "",
lastName: "",
phone: "",
address: ""
});
const { step, navigation, index } = useStep({ initialStep: 0, steps });
// Current Step
const currentStep: string = String(step);
// Props to different steps components
const props = { formData, setForm, navigation };
// Here you can make your request
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log({
email: formData.email,
username: formData.username,
password: formData.password,
name: formData.name,
lastName: formData.lastName,
phone: formData.phone,
address: formData.address
});
};
return (
<form method="POST" onSubmit={handleSubmit} className="Form">
<ProgressBar
index={index}
steps={[
{ id: 0, title: "Authentication" },
{ id: 1, title: "Basic Information" },
{ id: 2, title: "Contact Information" },
{ id: 3, title: "Review" }
]}
/>
<section className="container">
{/* Switch between different steps */}
{(() => {
switch (currentStep) {
case "auth":
return <AuthInfo {...props} />;
case "basicInfo":
return <BasicInfo {...props} />;
case "contact":
return <ContactInfo {...props} />;
case "review":
return <FormReview {...props} />;
default:
return null;
}
})()}
</section>
</form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment