Written by: Geoffrey Callaghan
How To Create A Contact Form With Netlfy
How To Create A Contact Form With Netlfy
Creating a contact form with Netlify involves a few steps, including setting up the HTML form, configuring form handling with Netlify, and optionally adding custom styling or functionality. Here’s a detailed guide to help you get started:
First, create an HTML file for your contact form. Here’s a basic example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
</head>
<body>
<h1>Contact Us</h1>
<form name="contact" method="POST" data-netlify="true">
<input type="hidden" name="form-name" value="contact">
<p>
<label>Name: <input type="text" name="name" required></label>
</p>
<p>
<label>Email: <input type="email" name="email" required></label>
</p>
<p>
<label>Message: <textarea name="message" required></textarea></label>
</p>
<p>
<button type="submit">Send</button>
</p>
</form>
</body>
</html>
To enable Netlify to process your form submissions, make sure you include the data-netlify="true"
attribute in your form tag. Additionally, add a hidden input with the name form-name
and value matching the form’s name attribute.
Push your project to GitHub, GitLab, or Bitbucket: Ensure your HTML file is part of a repository on one of these platforms.
Connect your repository to Netlify:
Deploy the site:
After deploying your site, navigate to the URL provided by Netlify and test your form by submitting a message. You can check the form submissions in your Netlify dashboard under the “Forms” section.
Here’s an example of adding basic CSS styling:
<style>
body {
font-family: Arial, sans-serif;
margin: 50px;
}
form {
max-width: 500px;
margin: 0 auto;
}
p {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
}
input, textarea {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
button {
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
</style>
If you want to handle the form submission using JavaScript (e.g., to avoid a full page reload), you can do something like this:
<script>
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
const formData = new FormData(this);
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(formData).toString()
}).then(() => {
alert("Form successfully submitted");
}).catch((error) => {
alert("Error submitting form");
});
});
</script>
With these steps, you’ll have a fully functional contact form deployed on Netlify, capable of handling submissions effectively.