greyskies
greyskies

Reputation: 271

How can I write php scripts in react.js file?

I've looked all over SO but the answers I'm seeing aren't clear for me. I've designed a nice UI/UX using react.js for my project but now I want to start hooking up some backend stuff to it using php.

I'm aware you can make ajax calls to fetch data but that still wouldn't allow me to do something like: <p><?php echo "testing; ?></p> in a react.js file.

Maybe my understanding isn't clear but I'd love some clarification because what I'm seeing online doesn't suffice for me.

Is it possible to write php scripts in a react.js file?

Also, I saw this link: https://github.com/reactjs/react-php-v8js but again, it isn't clear.

My apologies in advance if this doesn't satisfy the question standards on SO, I'm just really stuck and have nobody to turn to IRL other than SO. Thanks :-)

Upvotes: 0

Views: 4703

Answers (1)

Miguel Angel Mendoza
Miguel Angel Mendoza

Reputation: 1312

With reactjs you have to use different approach to the one used for php programing. Reactjs is the frontend, and php side is the backend or api. (I mean you do not have to render js on php, only your response on application / json)

To do that you can use * either axios or fetch* on reactjs app to request to the backend. With the response returned by the backend you will set a new state on your react component.

I will add a basic example:

React App:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: null,
    };
  }

  componentDidMount() {
    fetch('https://api.mydomain.com')
      .then(response => response.json())
      .then(data => this.setState({ data }));
  }

  ...
}

export default App;

Server side:

<?php
$response = [
   'items' => [
        [
            'product': 'MY PRODUCT 1',
            'code': '10001',
            'price': 39
        ],
        [
            'product': 'MY PRODUCT 2',
            'code': '10002',
            'price': 99
        ]
   ]
];

header('Content-Type: application/json');
echo json_encode($response);

I hope this can help you. :-)

Upvotes: 1

Related Questions