Simple React Form Example

This form will post ‘name and surname’ values to our PHP endpoint. It’s an ***extremely*** simple example which uses fetch to post data to our endpoint using get method.

Let’s start with our simple database.

First of all we need to create our SQLite database. I recommend to use https://sqlitebrowser.org/ Download it and create a database called my.db and table called names with two columns ; name and surname as text type. We will put our db near endpoint.php file where we serving our endpoint.

CREATE TABLE "names" (
	"name"   TEXT,
	"surname"   TEXT
);

Create our php endpoint as endpoint.php . It’s serving on 127.0.0.1 with EasyPHP. (Be sure that you put my.db near it)

<?php

error_reporting(0);

$name = $_GET['name'];
$surname = $_GET['surname'];

if (!empty($name) && !empty($surname)) {
$db = new SQLite3('my.db');
$db->exec("INSERT INTO names VALUES ('$name','$surname')");
echo "done";
}
else {
echo "name or surname is empty";
}

Finally, let’s create our React project somewhere else. Come in to CMD.

npx create-react-app your_app

Edit your_app/src/App.js file

import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {name: '', surname: ''};
    this.handleNameChange = this.handleNameChange.bind(this);
    this.handleSurnameChange = this.handleSurnameChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleNameChange(event) {
    this.setState({name: event.target.value});
  }
  handleSurnameChange(event) {
    this.setState({surname: event.target.value});
  }

  handleSubmit(event) {
    fetch('http://127.0.0.1/endpoint.php?name='+this.state.name+'&surname='+this.state.surname);
    alert('Done!');
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
      <label>
        Name:
        <input type="text" value={this.state.name} onChange={this.handleNameChange} />
      </label>
      <label>
        Surname:
        <input type="text" value={this.state.surname} onChange={this.handleSurnameChange} />
      </label>
      <input type="submit" value="Submit" />
    </form>
    );
  }
}

You can test this example with

npm start

Note: If you want to use POST method instead of GET method, you can change fetch like that.

 fetch('http://127.0.0.1/endpoint.php', { 
    method: 'POST',
    mode: 'cors',
    cache: 'no-cache',
    headers: {
      'Content-Type' : 'application/x-www-form-urlencoded',
    },
    body: "name=" + this.state.name + "&surname=" + this.state.surname,
    });