1

I'm adding react.js to a section of my app and am trying to embed some php code into react.js in order to not have to rewrite my whole backend which I had written in php. The idea would be something like the following:

...render(){
  return(
    <h1><?php echo "hello world"; ?></h1>
  )
}...

Unfortunately, this does not compile. I have tried every possible permutation I can think of and nothing will work, yet I feel this must be possible. Thanks!

Felix

GregarityNow
  • 707
  • 1
  • 11
  • 25
  • 2
    Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Shira Mar 27 '17 at 16:51
  • interesting I'll check that out – GregarityNow Mar 27 '17 at 16:53
  • Why would you expect this to work? That looks like a React component in a JavaScript file. PHP is designed to generate static HTML markup and wouldn't ever normally work if you embed it in a JS file. – Dan Prince Mar 27 '17 at 16:56
  • I don't know much about react but the xml-like syntax led me to posit that it could. My goal is to write the front end of this section of my app in react rather than js/jquery (I have never practically used react before). What I am really hoping for is to loop through data fetched from the server in html blocks (for example to put each item in an array in a header) – GregarityNow Mar 27 '17 at 17:01
  • your PHP parts can be switched to be an ajax call to your backend that returns either string of a component or json data. – r4ccoon Mar 27 '17 at 17:14

2 Answers2

1

If you want server side rendering? Check it out react-php-v8js

Emre Gozel
  • 45
  • 2
  • 7
0

You could have PHP output your JS but you absolutely positively shouldn't. You could also make ajax calls like everyone else to fetch data from external sources such as a PHP script.

Maybe something along the lines of:

...componentDidMount() {
    fetch("http://example.com/data.php")
    .then(response => response.json())
    .then(result => this.setState(result));
}...

...render() {
    return(
       <div>{this.state.result && this.state.result.foo}</div>
    );
}...

You're going to need to rebuild your current HTML output from PHP as React components. PHP now becomes a web service that looks something like this:

<?php // Business logic goes here: $data=new stdClass(); $data->name="Uzebeckatrente"; $data->foo="bar"; echo json_encode($data);

Lumen/Laravel is my personal choice of PHP platforms for web services.

Matt
  • 5,315
  • 1
  • 30
  • 57