Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Created August 7, 2021 07:27
Show Gist options
  • Save sagar-gavhane/5caecc45042a48f152e2ac159303d99f to your computer and use it in GitHub Desktop.
Save sagar-gavhane/5caecc45042a48f152e2ac159303d99f to your computer and use it in GitHub Desktop.
use form to generate multiple forms with different submit button
import { useState } from "react";
import { useForm } from "react-hook-form";
function MyForm() {
const { register, handleSubmit } = useForm({
defaultValues: {
title: "",
description: ""
}
});
const onSubmit = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
placeholder="title"
{...register("title", {
required: true
})}
/>
<input
placeholder="description"
{...register("description", {
required: true
})}
/>
<button>submit me</button>
</form>
);
}
export default function App() {
const [testCount, setTestCount] = useState(0);
return (
<div>
<button
onClick={() => {
setTestCount((_testCount) => _testCount + 1);
}}
>
add new form
</button>
{new Array(testCount).fill(null).map((_, idx) => {
return <MyForm key={idx} />;
})}
</div>
);
}
@sagar-gavhane
Copy link
Author

2nd solution with nanoid

import { useState } from "react";
import { useForm } from "react-hook-form";
import { nanoid } from "nanoid";

function MyForm() {
  const { register, handleSubmit } = useForm({
    defaultValues: {
      title: "",
      description: ""
    }
  });

  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        placeholder="title"
        {...register("title", {
          required: true
        })}
      />
      <input
        placeholder="description"
        {...register("description", {
          required: true
        })}
      />
      <button>submit me</button>
    </form>
  );
}

export default function App() {
  const [tests, setTests] = useState([]);

  return (
    <div>
      <button
        onClick={() => {
          setTests((_tests) => _tests.concat(nanoid()));
        }}
      >
        add new form
      </button>
      {tests.map((test) => (
        <MyForm key={test} />
      ))}
    </div>
  );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment