0

I'm wondering what the best way to pass data that was fetched by PHP from a MySQL server to a React component is. Currently the only way I know is to simply echo the variable into the prop value, but I feel like there surely has to be a better way than this as it feels very hacky.

I am new to React and have been looking for an API to use but haven't been able to find it (if it exists). I've also looked in the React documentation but it doesn't give any information either.

Below is a very basic example of what I've been doing so far:

<?php
class User {
    //Name returned from mysql query.
    public $name = "Steve";
}

$user = new User;
?>

<!DOCTYPE html>
    <body>
        <div id="greeting-div"></div>
    </body>
</html>

And my React component just looks like this:

  var Greeting = React.createClass({
    render: function() {
      return (
        <p>Hello, {this.props.name}</p>
      )
    }
  });

  ReactDOM.render(
    <Greeting name="<?php echo json_encode($user->name); ?>"/>,
    document.getElementById('greeting-div')
  );

Is there a better way to do it or is this the right way?

1 Answer 1

2

You can add a variable called "name" like this

<!DOCTYPE html>
    <script>
    var name = "<?php echo json_encode($user->name); ?>";
    </script>
    <body>
        <div id="greeting-div"></div>
    </body>
</html>

And edit JS file like this

 ReactDOM.render(
    <Greeting name={name}/>,
    document.getElementById('greeting-div')
  );
Sign up to request clarification or add additional context in comments.

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.