Build a Contact Form with React and PHP

Build a contact form with React and use in your PHP or Wordpress Website!

There are many ways to create contact forms, Using HTML and jQuery or HTML and Javascript to choosing more modern frameworks like React.

Today we’ll try to do something a little different, in a modern way.

By the end of this post, you’ll have a fully working contact from you can integrate into Wordpress or your php website. I also published the final project in github, so you can download and play around with it.

Prerequisites? not really

For this tutorial you don’t have to be an expert in Javascript, React or PHP. Basic knowledge is enough to get the hang of this tutorial. I also won’t go into basic details like installing React and writing CSS code.

We will only be creating the frontEnd part, but I will show you how to build the backend part as well. For the backend part you need a web server like Apache or Nginx. Only the basic email sending will be done with php.

For Mac users the fastest way to setup a server is to download and install Mamp. I have already installed Mamp with Nginx. You don’t need any database for this because we are just sending emails to your mailbox without saving it in a database.

OK then, let’s get this party started!

Creating the React app

You should have create-react-app installed in your computer. If you don’t have create-react-app, you can install it via npm. Run this in your console.

npm install create-react-app

Let’s navigate to your project folder in console. Mine is:

cd ~/react-contact-form

To create the React app in the folder run this command:

create-react-app .

This will take a couple of seconds or minutes. Once it is done open the project with your favourite IDE or code editor. Mine is VSCode. Then open up App.js file in the ./src/App.js folder. You will see something like this :

alt text

Creating the contact form

Let’s clean up a bit. Delete everything inside the div with class App. Now your render method should looks like this.

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

Just an empty div.

Let’s create a basic form with two text inputs for the first and second name, one email input for the user email, one textarea for the message and of course the submit button.

<p>Contact Me</p>
<div>
<form action="/action_page.php">
<label>First Name</label>
<inputtype="text"id="fname"name="firstname"placeholder="Your name.."/>
<label>Last Name</label>
<input type="text"id="lname" name="lastname" placeholder="Your last name.."/>


<label>Email</label>
<inputtype="email"id="email"name="email"placeholder="Your email"/>


<label>Subject</label>
<textarea id="subject"name="subject"placeholder="Write something.."></textarea>
<input type="submit"value="Submit"/>
</form>
</div>

Now your render method will look like this:

render() {
  return (
    <div className="App">
    <p>Contact Me</p>
    <div>
    <form action="/action_page.php">
    <label>First Name</label>
    <input type="text" id="fname" name="firstname" placeholder="Your name.." />
    <label>Last Name</label>
    <input type="text" id="lname" name="lastname" placeholder="Your last name.." />


    <label>Email</label>
    <input type="email" id="email" name="email" placeholder="Your email" />


    <label>Subject</label>
    <textarea id="subject" name="subject" placeholder="Write something.."></textarea>
    <input type="submit" value="Submit" />
    </form>
    </div>
    </div>
  );
}

Adding basic styling to your form

Create React app has already imported a CSS file by default. You can see App.css file in the ./src folder. Open it up and delete everything inside the file. Add this CSS code to the file. I’m not gonna explain what all the CSS does. But it’s pretty basic, just adding some widths and aligning.

* {
    box-sizing: border-box;
}
 .App {
     max-width: 420px;
     margin: 0 auto;
}
 p {
     text-align: center;
     font-weight: 500;
}
 input[type=text],input[type=email], select, textarea {
     width: 100%;
     padding: 12px;
     border: 1px solid #ccc;
     border-radius: 4px;
     box-sizing: border-box;
     margin-top: 6px;
     margin-bottom: 16px;
     resize: vertical;
}
 input[type=submit] {
     background-color: #4CAF50;
     color: white;
     padding: 12px 20px;
     border: none;
     border-radius: 4px;
     cursor: pointer;
}
 input[type=submit]:hover {
     background-color: #45a049;
}
 .container {
     border-radius: 5px;
     background-color: #f2f2f2;
     padding: 20px;
}

Okay. I don’t wanna confuse you too much. We did a bit of coding but have not seen any output yet. So let’s save everything and go back to the terminal. In the project root folder run:

npm start

This will open up the browser with localhost:3000 port. Now you will be able to see our cute little form like this.

alt text

Okay, great. Now it’s time for some real React stuff.

Handling the form with React!

Now we have a basic static React form. But it doesn’t do anything yet. We will need an initial state and submit handler function.

Form state

Now we will add a state for our form. We should create a constructor for this:

constructor(props) {
  super(props);
  this.state = {
    fname: '',
    lname: '',
    email: '',
    message: '',
  }
}

Then we need our form submit handler method like this:

handleFormSubmit( event ) {
  event.preventDefault();
  console.log(this.state);
}

For now we can log the state to see if we have all the values saved in the state.

Finally, let’s bind the form handler.

constructor(props) {
  super(props);
  this.state = {
    fname: '',
    lname: '',
    email: '',
    message: '',
  }
}

Now we have to set our initial states as form input values, and whenever changing our input we will set our state to the current input value.

At this point we change our form like this:

<formaction="#" >
  <label>First Name</label>
  <input type="text" id="fname" name="firstname" placeholder="Your name.."
    value={this.state.fname}
    onChange={e => this.setState({ fname: e.target.value })}
  />
  <label>Last Name</label>
  <input type=" text" id="lname" name="lastname" placeholder="Your last name.."
    value={this.state.lname}
    onChange={e => this.setState({ lname: e.target.value })}
  />


  <label>Email</label>
  <input type="email" id="email" name="email" placeholder="Your email"
    value={this.state.email}
    onChange={e => this.setState({ email: e.target.value })}
  />


  <label>Message</label>
  <textarea id="message" name="message" placeholder="Write something.."
    onChange={e => this.setState({ message: e.target.value })}
    value={this.state.message}
  ></textarea>
  <input type="submit" onClick={e => this.handleFormSubmit(e)} value="Submit" />
</form >

If you try to write something in the form and try to submit it now, you will see your data in the console. Open your console and check if it works. The console output should look like this.

alt text

Send an email with PHP

Well. We are almost done with the frontend part. Now we need a server side language to send emails to our mailbox. I choose php this time. Before we start writing the backend part let’s add two more properties to our state. We need to add { error and mailSent }.

this.state = {
  fname: '',
  lname: '',
  email: '',
  message: '',
  mailSent: false,
  error: null
}

The state is ready. Let’s start with php. If you created your react app already in Apache or Nginx www folder, you can go to your project root and create a folder called api/contact inside the contact folder.

Create an index.php file. Our email function will live here. I wanna mention that we are not going to use OOP approach. But if you want a cleaner php code, you can clean up and improve it a little bit.

From the React app we are sending a post request to php api. In our contact form the first name and email should be required. Because in php we are gonna check for those two values. If these two values are empty we are going to throw an error. So keep it in mind.

Let’s add this code to your index.php file.

<?php
header("Access-Control-Allow-Origin: *");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

if (empty($_POST['fname']) && empty($_POST['email'])) die();

if ($_POST)
	{

	// set response code - 200 OK

	http_response_code(200);
	$subject = $_POST['fname'];
	$to = "[email protected]";
	$from = $_POST['email'];

	// data

	$msg = $_POST['number'] . $_POST['message'];

	// Headers

	$headers = "MIME-Version: 1.0\r\n";
	$headers.= "Content-type: text/html; charset=UTF-8\r\n";
	$headers.= "From: <" . $from . ">";
	mail($to, $subject, $msg, $headers);

	// echo json_encode( $_POST );

	echojson_encode(array(
		"sent" => true
	));
	}
  else
	{

	// tell the user about error

	echojson_encode(["sent" => false, "message" => "Something went wrong"]);
	}

?>

Basically what we are doing is: We are checking for the first name and email. Then using the php mail() function, we are sending an email to our email account with the contact form data.

Now if you navigate to your api folder http://localhost/react-contact-form/api/contact

…you should see nothing. Because our api is dying, if we don’t send the first name and email as well — it’s looking for a post request.

Sending the data to an API

Our API is ready and now it’s time for finishing up our form. So we need to send our data that has been saved in the state. We can use Javascript fetch for this. But recently I was using another npm package that works very well with React for http requests. Maybe you already know about it ‘Axios’. So we need to install this package first. Go to your React app folder in the console.

And execute:

npm install axios

Great. Now go back to App.js and on the top of the file you have to import Axios.

import axios from 'axios';

After importing Axios we have to create a constant for our api path. Create the constant before the App class.

const API_PATH = 'http://localhost:1992/react-contact-form/api/contact/index.php';

Then let’s use Axios inside the handleFormSubmit method to send our data to the backend.

handleFormSubmit = e => {
  e.preventDefault();
  axios({
    method: 'post',
    url: `${API_PATH}`,
    headers: { 'content-type': 'application/json' },
    data: this.state
  })
    .then(result => {
      this.setState({
        mailSent: result.data.sent
      })
    })
    .catch(error => this.setState({ error: error.message }));
};

Now we should be able to send emails via our contact form. Finally, let’s show a message to the user after they sent the email.

Before the form closing tag </form>, add this.

<div>
  {this.state.mailSent &&
    <div>Thank you for contcting us.</div>
  }
</div>

Now our user is able to see a message after sending the email. All done! You have a cute little contact form with React and php.

Documentation and github repo you can find here: https://github.com/malithmcr/react-php-contact-form

Watch the video to understand the usage of GitHub repo:

IMAGE ALT TEXT HERE

Final look

alt text

Conclusion

Thanks for reading! I hope this article provides some insight into how easy it is to use React and php to create a simple contact form. I encourage you to change or try and improve the React part. Maybe even add a loader and play around with the styling.

If you have any questions or remarks, leave a comment below. Thanks again for reading!

Get The Best Of All Hands Delivered To Your Inbox

Subscribe to our newsletter and stay updated.