sleeveroller sleeveroller - 3 months ago 8
React JSX Question

Why React.Component only rendering once even when I have multiple target elements

I'm trying to create a widget with React that would render many times one a page (say a special button widget).

I'm defining my classes in ES6 style like this:

export default class myWidget extends React.Component{

..."constructor and other methods"....

render(){
return <div className="myButtonStyles">Click me</div>;
}

}


My html simply have several identical elements and jQuery selector:

$(document).ready(function(){
$.each($('.myWidget'), function(index, element){
ReactDOM.render(
<App/>,
element
);
})
});

<div>First one <span class="myWidget"/></div>
<div>Second one <span class="myWidget"/></div>
<div>A third <span class="myWidget"/></div>


When running my code, I get the first one rendered only. No Errors!

I experimented with React.createClass instead and seems to be rendering three times.

What am I missing with React? Any help appreciated.

Answer

You should change your span tag to <span class="myWidget"></span>

it works , you can check ---> jsbin

variant with $(document).ready ---> jsbin

class Block extends React.Component {
    render(){
        return (<div>Block</div>);
    }
}

$(document).ready(function(){
    $.each($('.block'), function(index, element){
        ReactDOM.render(
           <Block/>,
           element
        );
    })
});

///html

<body>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
  <div class="block"></div>
</body>
Comments