DEV Community

Cover image for Building a Contact Form with React and PHP
Abdul Haseeb
Abdul Haseeb

Posted on

Building a Contact Form with React and PHP

Introduction:
In this tutorial, we'll create a simple contact form using React for the frontend and PHP for the backend. This project will help you understand how to handle form inputs in React, style components with CSS, and send form data to a server using JavaScript. On the server side, we'll use PHP to process the form data and send an email.

Prerequisites:

  • Basic knowledge of HTML, CSS, JavaScript, and React.
  • A local server environment like XAMPP or MAMP to run PHP scripts.
  • A code editor like VS Code.

Step 1: Setting Up the Project
First, let's set up our React project using Create React App. Open your terminal and run the following commands:

npx create-react-app contact-form
cd contact-form
npm start
Enter fullscreen mode Exit fullscreen mode

This will create a new React project and start the development server. Open your browser and navigate to http://localhost:3000 to see the default React app.

Step 2: Creating the Contact Form Component
Next, we'll create a new component for our contact form. Create a new file called ContactForm.js in the src directory and add the following code:

import React, { useState } from 'react';
import './ContactForm.css';

function ContactForm() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [message, setMessage] = useState('');
  const [response, setResponse] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('name', name);
    formData.append('email', email);
    formData.append('message', message);

    const res = await fetch('http://localhost/contact-form-server/submit.php', {
      method: 'POST',
      body: formData
    });

    const result = await res.json();
    setResponse(result.message);
  };

  return (
    <div className="contact-form">
      <h1>Contact Us</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Your Name"
          required
        />
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Your Email"
          required
        />
        <textarea
          value={message}
          onChange={(e) => setMessage(e.target.value)}
          placeholder="Your Message"
          required
        ></textarea>
        <button type="submit">Send</button>
      </form>
      {response && <p>{response}</p>}
    </div>
  );
}

export default ContactForm;
Enter fullscreen mode Exit fullscreen mode

Step 3: Adding Some Styling
To make our form look better, let's add some basic styling. Create a new file called ContactForm.css in the src directory and add the following styles:

.contact-form {
  width: 300px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background: #f9f9f9;
}

.contact-form h1 {
  margin-bottom: 20px;
}

.contact-form input,
.contact-form textarea {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

.contact-form button {
  width: 100%;
  padding: 10px;
  background: #007bff;
  color: #fff;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.contact-form button:hover {
  background: #0056b3;
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Using the Contact Form Component in App.js
Now, let's use our ContactForm component in the main App.js file. Open src/App.js and update it as follows:

import React from 'react';
import ContactForm from './ContactForm';
import './App.css';

function App() {
  return (
    <div className="App">
      <ContactForm />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 5: Setting Up the PHP Server
Create a directory called contact-form-server in your server's root directory (e.g., htdocs for XAMPP). Inside this directory, create a file named submit.php and add the following code:

<?php
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // Normally, you would send the email here using mail() or a library like PHPMailer
    // For this example, we'll just return a success message

    echo json_encode(['message' => 'Thank you, ' . $name . '! Your message has been sent.']);
} else {
    echo json_encode(['message' => 'Invalid request method.']);
}
?>
Enter fullscreen mode Exit fullscreen mode

Conclusion:
That's it! You've built a simple contact form with React and PHP. This form captures user input and sends it to a PHP script on the server, which processes the data and sends a response back to the frontend. You can now extend this app by adding features like form validation, error handling, and real email sending.

Further Reading:


This tutorial covers setting up a React project, creating a component with a form, styling it with CSS, and sending form data to a PHP backend. Adjust the complexity and depth based on your target audience's experience level.

Top comments (0)