Environment Setup:
REACT:
React is a library for building user interfaces, originally created by group of Facebook engineers. React as the V(View) in MVC. React Official Website
Install Node.js and npm. Download. Once installation done, you can verify both node and npm functioning by opening command and typing node -v and npm -v, which will display the version number.
PHP & MySQL (API Service):
PHP is a popular general-purpose scripting language that is especially suited to web development. PHP Official Website. MySQL is a specialized database software program that makes storing and retrieving data as efficient as possible. MySQL Official Website.
Use the Installation Guide (LAMP Stack), to install PHP and MySQL. Ignore, if setup is already done in your local environment.
Integration Process:
1. Creating React application using ‘create-react-app’ toolchain
Create React App is a comfortable environment to create a single-page React applications. It offers a modern build setup with no configuration. create-react-app to bootstrap a React application on your own computer. npx is a package runner tool that comes with npm 5.2+ and higher.
npx create-react-app dynamic-app
“create-react-app” will generate the initial project structure like below,
dynamic-app
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ └── manifest.json
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
├── setupTests.js
└── serviceWorker.js
Execute the below command to start the project in your local environment, and make sure your executing the command on the root folder (i.e., dynamic-app folder in our case).
npm start
After the command execution, a window will popup at http://localhost:3000 with new React app.
2. HTTP Requests with Axios Library
Axios is a Promise-based HTTP client for the browser and node.js platform. It provides support for request and response interceptors, transformers and automatic conversion to JSON. Install the package using below command.
$ npm install axios
Sample Axios GET request code (service.js):
import axios from "axios";
const BASEURL = "http://localhost/workspace/api"; //Local PHP Root Path
const standardAxios = axios.create({
baseURL: BASEURL,
headers: {
"X-Requested-With": "XMLHttpRequest",
"Content-type": "application/json",
},
});
export const getRequest = (params, requestUrl) => {
standardAxios
.get(requestUrl, { params: params })
.then((res) => {
if (res.status === 200) {
console.log(res.data);
} else {
console.log('Failed');
}
})
.catch((err) => {
console.log('Error')
return false;
});
return true;
};
3. PHP & MySQL API Codebase:
Add below files into PHP Workspace, make sure apache server the up and running.
MySQL Connection File (connection.php / file-1)
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
class Connection {
public function getConnection(){
$host = "localhost:3306";
$db = "api";
$user = "root";
$pass = "********";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$db = new PDO("mysql:host=$host;dbname=$db;", $user, $pass, $options);
return $db;
}
}
?>
Below PHP code will return JSON response (sampleJSONData.php / file-2)
<?php
include('connection.php');
$result = [];
try {
$model = new Connection();
$db = $model->getConnection();
$sql = "SELECT id FROM sample_table";
$query = $db->prepare($sql);
$query->execute();
if ($query->rowCount() > 1) {
$sample_row = $query->fetch(PDO::FETCH_ASSOC);
$result["records"]= array(
'id' => $sample_row["id"]
);
}
echo json_encode($result);
} catch(PDOException $error) {
//catch error
$result["status"] = $error->getCode();
$result["message"] = $error->getMessage();
echo json_encode($result);
}
?>
Now, you can call below request function in you JS root file.
const sampleData = getRequest({}, 'sampleJSONData.php');