1

I have 2 questions with respective re-usable React Components.

  1. I would like to have to React Component which should take the props object from the data- attribute from the HTML, this should happen onload instead of event. The examples shown in the React Docs use props within the ReactDOM.render method. I couldn't find an example where we retrieve props from data attributes.

  2. I would also like to reuse the React Component without duplicating the ReactDOM.render, instead just change the props and mount the component(s) based on their class name.

[Sample Example] I have the HTML markup as,

<div class="blog" id="Politics" data-title="Political Science"></div>
<p>
Some description text..
</p>
<div class="blog" id="Economics" data-title="World Economy"></div>

The React Component is,

var propTitle = {
  'title': getTitle() //Function to retrieve data-title from respective component.
};
var Blog = React.createClass({
  render: function() {
    return (
      <h3>
        {this.props.blogtitle} 
      </h3>
    )
  }
}); 

ReactDOM.render(<Blog blogtitle={propTitle.title}/>,document.querySelectorAll('.blog'));

For convenience, JSFiddle is here!

1 Answer 1

2

Something like this?

var blogs = document.querySelectorAll('.blog');
for(var i = 0; i < blogs.length; i++){
    createComponent(blogs[i]);
}

function createComponent(blog){
    ReactDOM.render(<Blog blogtitle={blog.dataset.title} />, blog)
}

Fiddle: https://jsfiddle.net/rtLux0f6/1/

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.