GregarityNow
GregarityNow

Reputation: 738

embed PHP in react js

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

Upvotes: 1

Views: 9602

Answers (2)

Matt
Matt

Reputation: 5428

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.

Upvotes: 0

Emre Gozel
Emre Gozel

Reputation: 45

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

Upvotes: 1

Related Questions