How to use React in a php 8 project

How to integrate react with php 8 project

Posted by Margie Crona on December 11, 2021

In this short lesson you will be shown how to integrate React with a php project. 

This will be a continuation of tutorial "How to install webpack to a PHP project". Therefore, before we start, please go to https://wecode101.com/how-to-install-webpack-to-a-php-project in order to understand how to integrate webpack in your PHP project. Webpack will be used to install React to PHP in this project. 

You can also download the project from that tutorial and follow along with this react php example.

However, you should be able to follow this lesson and successfully integrate React if you have a PHP project other than the Slim framework with a similar set up.

Step 1. Install React to the project

cd to project root and run commands below:

npm install react react-dom

npm install babel-loader @babel/core @babel/preset-react --save-dev

Step 2. Add directory to hold React files

Create js directory in /app/assets

Step 3. Add a react file home.js to the js directory

Place below code snippet in home.js:

import React, {Component} from "react";
import ReactDOM from 'react-dom';

class App extends Component {

    render () {
        return (
            <h1>PHP with react</h1>
        );
    }
}

export default App;

ReactDOM.render(<App/>, document.getElementById('root'));

The code snippet above will render react on the PHP page.

Step 4. Add React configuration to Webpack

Add code snippet below to webpack.config.js in module object within module.exports:

{
  test: /\.?js$/,
  exclude: /node_modules/,
  use: {
     loader: "babel-loader",
        options: {
        presets: ['@babel/preset-react']
     }
  }
},

Step 5. Add React file path to be compiled by Webpack

Add path to webpack.config.js the entry property value within module.exports

entry: ["./app/assets/sass/app.scss", "./app/assets/js/home.js"],

Step 6. Place HTML script in the place you want React to appear:

<div id="root"></div>

Step 7. Add the path of the app.js file that will contain the compiled React file in the footer of your project or in the footer.

<script src="<?= $baseUrl; ?>assets/js/app.js"></script>

If you are following along with the project from previous tutorial remove this line of script from the header to the footer. 

Step 8. Execute npm run dev from root of project

Launch your project and you should now see the text on your page.