MartaGom MartaGom - 1 month ago 14
React JSX Question

Generate ReactJS inside PHP Loop

I'm a complete novice with REACT, especially to extract information from the server. I don't have any API inside my backend, so... Can I generate react code as follow?

Example of my component:

var Test= React.createClass({

render: function () {
return (
<div>
<p>
This is my test: {this.props.name}
</p>
</div>
);
}
});


How I think I can "render" this react component with a PHP Loop:

<script type="text/babel">
<?php foreach($tests as $test){ ?>

ReactDOM.render(

<div className="text-center">
<Test name="Test 1" />
<Test name="laralala" />
</div>

,document.getElementById("test")
);


<?php} ?>
</script>


But I think the previous "way" it's a complete bad practice... Can someone help me a little? My intention is not to have to change anything in the backend ...

Thank you very much.

Answer

Accessing data from PHP

One possible solution would be to put your data (generated by PHP) into the generated HTML page as global/static JS variables, like var data = <?php echo json_encode($data); ?>;.

As long as you only need the data initially this will work fine. The issue you will run into is that you have to reload your page every time $data was updated (by a form for example). This kinda goes agains all this "single page application" logic. But I guess if you do not have an API, you're stuck with this solution.

@SPA

React currently is all the rage. But if you do not need all its power (beeing a SPA with routing, client-side state, ...) I would suggest just using something simple, yet powerful, like jQuery. Using it is fine, even in 2016. You also could look into Polymer or Web Components.

If you do not already know React and only need it to render some HTML, I don't think you should have to learn it. There are other good alternatives to render dynamic HTML (isn't that what PHP was mode for initially?!).

Comments