I made a contact form including name, email, content and file using Next.js.
But it is no longer in progress because can’t upload files using post api.
I thought it will be simple, but it isn’t.
Please heip me…
NODE Version
v16.14.2
STRAPI Version
v4.1.2
Cloudinary
Here are the codes.
import { useState } from "react";
import { useRouter } from "next/router";
import baseApiUrl from "../utils/baseApiUrl";
const Contact = () => {
const router = useRouter();
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [content, setContent] = useState("");
const [file, setFile] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
const data = {
name,
email,
content,
file,
};
fetch(`${baseApiUrl}/api/contacts`, {
method: "POST",
headers: {
//"Content-Type": "multipart/form-data",
"Content-Type": "application/json",
},
body: JSON.stringify({
data: {
name: `${data.name}`,
email: `${data.email}`,
content: `${data.content}`,
file: `${data.file[0]}`,
},
}),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
});
};
return (
<section id="contact" className="contact">
<div className="wrap container">
<h2>CONTACT US</h2>
<div className="form_wrap">
<div className="form_box">
<form name="contact-form" onSubmit={handleSubmit}>
<ul>
<li>
<label htmlFor="name">Name</label>
<input
id="name"
name="name"
required
type="text"
onChange={(e) => setName(e.target.value)}
/>
</li>
<li>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
required
type="email"
onChange={(e) => setEmail(e.target.value)}
/>
</li>
<li>
<label htmlFor="content">Content</label>
<textarea
id="content"
name="content"
onChange={(e) => setContent(e.target.value)}
></textarea>
</li>
<li>
<label htmlFor="file">File</label>
<input
id="file"
name="file"
type="file"
onChange={(e) => setFile(e.target.files[0])}
></input>
</li>
</ul>
<button type="submit" className="submit">
Submit
</button>
</form>
</div>
</div>
</div>
</section>
);
};
export default Contact;