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. -> 😉 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() {
     <div className="App">


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>



<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.."/>


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


<textarea id="subject"name="subject"placeholder="Write something.."></textarea>

<input type="submit"value="Submit"/>



now your render method will look like this:


render() {

return (

<div className="App">

<p>Contact Me</p>


<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.." />


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


<textarea id="subject" name="subject" placeholder="Write something.."></textarea>

<input type="submit" value="Submit" />






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) {


    fname: '',
    lname: '',
    email: '',
    message: '',


Then we need our form submit handler method. Let’s create it.


handleFormSubmit( event ) {

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) {

   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:



<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.."





<input type="email" id="email" name="email" placeholder="Your email"





<textarea id="message" name="message" placeholder="Write something.."




<input type="submit" onClick={e=>this.handleFormSubmit(e)} value="Submit"/>


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.

  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.



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








$headers="MIME-Version: 1.0\r\n";

$headers.="Content-type: text/html; charset=UTF-8\r\n";

$headers.="From: <".$from.">";


//echo json_encode( $_POST );


} else {

// tell the user about error




"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 => {
  method: 'post',
  url: `${API_PATH}`,
  headers: { 'content-type': 'application/json' },
 data: this.state
.then(result=>{ this.setState({
.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>Thank you for contcting us.</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 :

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


Wp post images – Awesome custom image uploader for WordPress posts.

During my free time I had sometime to create another free wordpress plugin. This plugin allow you to upload images in your post without any limit. I’m still working on this plugin and there are lot more to improve to do. But I’ll get there. You can create a PR or request any change.

Version and development

Download : on github

How to start :

First download the plugin from github.Go to wordpress
admin->plugins->add new and
then upload the file.
>Activate plugin.

Go to your post and you can see image uploader from at right side of the post.

How to use

You can show images on frontend using shortcode.

In the post:

In php file:

"echo do_shortcode('');"

That’s it. Enjoy!

Feel free to create PR in github or write me a message if you have any question.


What I learned from the book: The road to learn React

Sometimes I like to play around with programming books. This time I wanted to give the book “The road to learn React” a try. I can recommend this book to anyone who starts learning react. At the end of this book, you will create a clone of the Hackernews website. You can see and download my hackernews clone here. Please follow this post to see how to run this project. Feel free to create PR on Github.


what I learned:


  • create-react-app bootstraps a React application
  • JSX mixes up HTML and JavaScript to define the output of React components in their render methods
  • Components, instances, and elements are different things in React
  • ReactDOM.render() is an entry point for a React application to hook React into the
  • PropTypes let you define type checks for components
  • Jest allows you to write unit tests for your components DOM
  • Built-in JavaScript functionalities can be used in JSX * map can be used to render a list of items as HTML elements
  • Hot module to see changes in the browser without reloading
  • Use this.state and setState() to manage your internal component state
  • Pass functions or class methods to your element handler
  • Use forms and events in React to add interactions
  • Embrace controlled components
  • Compose components with children and reusable components
  • Usage and implementation of ES6 class components and functional stateless components
  • Approaches to style your components
  • ES6 class component lifecycle methods for different use cases
  • ComponentDidMount() for API interactions
  • Conditional renderings
  • Synthetic events on forms
  • Error handling
  • Aborting remote API request


  • Variable declarations with const and let can be used for specific use cases
  • Use const over let in React applications
  • Arrow functions can be used to keep your functions concise
    classes are used to define components in React by extending them
  • Functions that are bound to a class are class methods
  • Destructuring of objects and arrays
  • Default parameters
  • Template strings to compose strings
  • Spread operator for immutable data structures
  • Computed property names
  • Class fields
  • Import and export statements help you to organize your code


  • Higher-order functions
  • Hacker news api interaction
  • Native fetch browser API
  • Client and server- side search
  • Pagination of data
  • Client-side caching
  • Axios as an alternative for the native fetch API
  • Code organization allows you to scale your application with the best practices

code Playground location src/CodePlayground.js

How to start the repo

You can clone the github repo and cd to hackernews run – npm install npm start test run - npm test


Enjoy this blog? Please spread the word :)