3

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?

| improve this question | | | | |
1

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}

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.