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

5
  • 2
    Possible duplicate of What is the difference between client-side and server-side programming? Commented Mar 27, 2017 at 16:51
  • interesting I'll check that out Commented Mar 27, 2017 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. Commented Mar 27, 2017 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) Commented Mar 27, 2017 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. Commented Mar 27, 2017 at 17:14

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.