Javascript – How to passing variables from php to react.js component

javascriptPHPreactjs

For example, I have a react.js component named Question which need the props title,id,content.

<div id="main-section">
    <div id="question"></div>
</div>

ReactDOM.render(
    <Question id="xxxx" title="xxx" content="xxx"/>,
    document.getElementById('question')
);

I come up with two methods:

  1. design an restful api, everytime the web need to render a question, make an ajax request to the server to get the props.
  2. store the props in dom element and get these props before rendering.

What's the best practise to do such thing? is there any other better method?

Best Answer

You can define you element first as a const/var or whatever. Then you access the element's attributes with element.attributes and iterate through your attributes like so:

const element = document.getElementById('question');

ReactDOM.render(
    <Question {...element.attributes} />,
    element
);

You can access the attributes with this.props

If you're passing data-* attributes your can pass those with {...element.dataset}

Related Topic