How to create a contact form with react js and php

Hello again, First of all thanks for stopping by.  There are many ways to create contact forms, like  using HTML and jQuery or HTML and Javascript. There is nothing wrong with using those technologies. But today we are gonna do it in modern way. For this tutorial you don’t have to be expert in javascript or react and php, but just basic knowledge is enough.  You can also integrate this form with wordpress or your php website. I’ll publish final project in github. You can download and play with it. I have to mention that I’m not gonna go into basic details like installing react and writing basic css code. If you don’t have those basic skills I suggest a great website  to start your learning. -> www.google.com 😉 This tutorial will not end only creating frontend part. But I will show you how to build the backend part too. Just the basic email sending with php. For the backend part you need a web server like apache or  Nginx. for mac users fastest way to setup a server is download and install mamp. I have already install mamp with nginx. You don’t need any database for this because we are just sending email to your mailbox without saving it in a database. Ok then, Let’s get the party started. Frontend frist:

1 )  Creating 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 ~/Sites/react-contact-form

to create the react app in the folder run this command:

create-react-app .

this will take couple seconds or minutes. Once it done open the project with your favorite 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 :

 

2 ) Creating contact form.

Let’s clean up a bit.  Let’s 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 first name 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>

<formaction="/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>

);

}

Let’s add basic styling to our form. Create react app 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 doing. But it’s pretty basic, Just adding some width’s and aligning it to center.

 

* {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 bit of coding  but never seen an 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.

 

Okay. great. Now time for some real react stuff.

 

3 ) Handle the form with react.

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

4) Form state.

Let’s create 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. Let’s create it.

 

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 change our for input we will set our state to current input value.

Let’s 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>

Now if you try to write something in the form and try to submit it,  you could see your data in the console. open your console and see if it works. Console output should look like this.

5)  send email with php.

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

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

So now 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 contact folder let’s create 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 cleaner php code you can clean up and improve little bit more this php code.

From react app we are sending post request to php api. In our contact form first name and email should be required. Because in php we are gonna check for these 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="me@malith.pro";

$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  first name and email then using php mail() function we are sending email to our email account with contact form data.

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

you should should see nothing. Because our api is dying if we don’t send first name and email also it’s looking for a post request.

6) Sending data to api.

Our api is ready and now time for finishing up our form. So we need to send our data that 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 console. And run

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 constant for our api path. Create constant before the App class.

const API_PATH = 'http://localhost:1992/react-contact-form/api/contact/index.php';
Then let’s use axios inside  handleFormSubmit method to send our data to 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 email via our contact form. Finally, Let’s show a message to user after they sending the email.

Before form closing tag </form>, Let’s 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! now you have cute little contact form with react and php.

 

Download the code from github : https://github.com/malithmcr/react-php-contact-form

Thank you again for visiting. Please don’t forget to press star icon in github repo.

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Hassan Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Hassan
Guest
Hassan

This is exactly what I was looking for. Thank you.

trackback

[…] This is code for tutorial in my blog post Create Contact form with react and php. […]

Enjoy this blog? Please spread the word :)