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.

0-0

New project – SpareTime Design

Recently I worked on this personal blog project for my client. This website includes a shop and a few other pages. I created the theme from scratch. Also a few plugins. If you are interested in graphic design, you can save this blog and read weekly. Also they provide free themes and vector graphics.

Live urlhttps://sparetime.design/

Tech Stack : WordPress, WooCommerce, Javascript , scss

Screenshot :

0-0

My favorite scss mixins and features

Ever since I started using SCSS/SASS, I knew I’d use this for all my future projects. It really helped me to write CSS in a meaningful way. I’m writing this post to share my favorite scss features and mixins. I use these every day for my current work.

This is not a tutorial about how to use scss. Just some very useful code snippets for scss.

  1. Mixin for media queryThis mixing help me to write responsive code for all of my projects.
    @mixin bp($feature, $value) {
    // Set global device param
    $media: only screen;
    // Media queries supported
    @if $feature == min-width{
    @media (min-width: #{$value}) {
    @content;
    }
    }@else if $feature == max-width{
    @media (max-width: #{$value}) {
    @content;
    }
    }@else{
    @media (min-width: #{$feature}) and (max-width: #{$value}) {
    @content;
    }
    }
    }Usage:

    * For min-width and max-width:
    * @include bp(350px ,750px)
    * For min-width:
    * @include bp(min-width, 200px)
    * For max-width:
    * @include bp(max-width, 750px)

  2. @import @import '_header'; Because of Import option my codebase looks very clean. It’s very easy to use. Similar to css import with scss import you can split your css into smaller chunks. But scss @import performance is faster than css @import. Because of css @import make a http request to each @import file. But scss combines all imported files and makes one single css file.
  3. Operators
    Sass allows you to use math operators in your stylesheet. Isn’t it so cool to use maths in css ? for example:$width : 200;
    @if (windowSize > 640) {
    font-size: (16px / 24px); // Outputs as CSS
    width : (20px * $width);
    }
  4. @extend
    Using @extend you can re-use same styling that has been used for other component.
    This avoid you to repeat writing same thing again, also known as ‘DRY’.
    .wishlist-icon {
    color: #000;
    background-color: #fff;
    }
    .user-icon {
    @extend .wishlist-icon;
    font-size: 12px;
    }
  5. Placeholder selectors This also works like @extend but little bit different. This will compile only if you ever use it.
    %footer-component {
    background: black;
    font-size: 12px;
    // and so on...
    }
    .left {
    @extend %footer-component;
    color: red;
    }
    .right {
    @extend %footer-component;
    color: white;
    }
    This will compiled to :.right, .left {
    background: black;
    font-size: 12px;
    }

    .left {
    color: red;
    }

    .right {
    color: white;
    }

That’s it for now guys. I’ll keep updating this list whenever I find a good scss feature.
check out my other posts or leave a comment here for support. Thank you so much.

0-0

Quick update!

Assuming you already read my post about post image plugin. I’m writing this quick update to tell you that my plugin is now available to download from wordpress directly.

WordPress plugin url : https://wordpress.org/plugins/awesome-post-images/#description

click here

Post about the plugin : http://blog.malith.pro/wp-post-images-awesome-custom-image-uploader-for-wordpress-posts/

click here

 

Thank you for all your support!

1-0

Code discipline – Rules for my codes.

I remember how many mistakes I made when I started to write programs and the times I was trying to be a programmer. That was a really tough time. Like every other programmer, we all suck in the beginning. Also we all learn, with practice and experience we write better code and understand difficult algorithms. I never stopped learning and becoming a better programmer. I still do so many stupid things. But from all those mistakes I learn something. Sometimes I know how it should be done but even then I don’t use what I know, maybe because of laziness or because I just don’t care. However I don’t wanna do it anymore. I decided to set some rules for myself when I write code next time.

My rules , My code

  • Always document my code, Comment. Comment. Comment.
  • Don’t write ninja code. Write human readable code.
  • Don’t follow the trend.
  • Prevent Deep Nesting.
  • Don’t push broken code
  • Write maintainable code.
  • Use less media queries and write media queries only when you need.
  • Use Appropriate Naming Convention for css.
  • Use JS Lint.
  • Use Flexbox and Grid in the future.
  • Follow a Proper Coding Standard.
  • Always handle errors.
  • Use DRY Approach.
  • Create something valuable and helpful to others.

For now this is it. But I will update this list again when I notice something I should do.

Thank you for reading guys, I recently did an experiment with content load animations like facebook. you can take a look here. Also press that star button ;).

0-0

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
1.0.0

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.

0-0

Enjoy this blog? Please spread the word :)