Search code examples
javascripthtmljqueryreactjscustom-data-attribute

Retrieve custom data-* attributes value in React Component(without event)


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!


Solution

  • 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/