NextJs / Form / Get FormData and pass to API
Get Form Data
-
1. Files
Option 1. using useState()
1. create form
2. add useState for form fields
3. apply onchange event in the input fieldimport { useState } from 'react'; ..... ....... const [email, setEmail] = useState(''); const [password, setPassword] = useState('');
4. add onSubmit() to form
5. define function 'onSubmit'
Complete codeasync function onSubmit(event: FormEvent ) { event.preventDefault() const response = await fetch('/api/submit', { method: 'POST', body: JSON.stringify({ email,password }), }) } import React from 'react'; import type { ReactElement } from 'react'; import { useState } from 'react'; import { useRouter } from 'next/router'; import { FormEvent } from 'react' // Import the reading layout import ReadingLayout from '@/components/ReadingLayout'; function read() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); async function onSubmit(event: FormEvent ) { event.preventDefault() const response = await fetch('/api/submit', { method: 'POST', body: JSON.stringify({ email,password }), }) } return (
{page} ) }Option 2: using FormData
1. create form and add name property to the input fields
2. in the onSubmit() use new FormData()
import Image from 'next/image'; import { Inter } from 'next/font/google'; import { FormEvent } from 'react' export default function Home() { async function onSubmit(event: FormEvent ) { event.preventDefault() const formData = new FormData(event.currentTarget) const response = await fetch('/api/submit', { method: 'POST', body: formData, }) // Handle response if necessary const data = await response.json() // ... } return ( ); } -
2. Advanced: useState for array
); }; export default MyForm;// components/MyForm.js import { useState } from 'react'; const MyForm = () => { const [formData, setFormData] = useState({ name: '', email: '', message: '' }); const handleChange = (e) => { const { name, value } = e.target; setFormData((prevData) => ({ ...prevData, [name]: value })); }; const handleSubmit = (e) => { e.preventDefault(); // Handle form submission here console.log('Form submitted:', formData); // You can add logic here to send the form data to a server, etc. }; return (