Reputation: 7562
In my application, I have a requirement to render same data into multiple places via react. So instead of rendering that via id (via below code), i want to use class tag.
ReactDOM.render(<App />, document.getElementById('app')); // Working
ReactDOM.render(<App />, $('.app')); // Not working.
My html is like below...
<div class="app" id="app"><div>
<div class="app"><div>
<div class="app"><div>
Update: below is my jsx file.
class PList extends React.Component {
static defaultProps = {
results: []
}
constructor(props) {
super(props);
this.state = {
results: this.props.results
};
}
render() {
return (
<ul>
{
this.state.results.map((item, i) => {
return <li>{item.Name}</li>
})
}
</ul>
);
}
}
var PRender = ReactDOM.render(<PList />, $('.app'));
function Professionals(data) {
PRender.setState({
results: data.Results
});
}
Upvotes: 1
Views: 1414
Reputation: 451
Here's the answer for your edition.
https://codesandbox.io/s/hopeful-payne-1tloe?fontsize=14
Same as @Alona's answer. I tried to use jQuery
-> $('.app')
which described on question.
function App({index}) {
return `<div>App - ${index}</div>`;
}
$.each($('.app'), (index, app) => ReactDOM.render(<App index={index + 1} />, app))
<html>
<div class="app" id="app"></div>
<div class="app"></div>
<div class="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
</html>
Upvotes: 2
Reputation: 549
$('.app')
- this is just an array, and ReactDOM.render
requires single element as second parameter.
You can try as following if you need to render multiple App
.
function App({index}) {
return `<div>App - ${index}</div>`;
}
document.querySelectorAll('.app').forEach((app, index) => ReactDOM.render(<App index={index + 1} />, app));
<html>
<div id="app">No ID assigned to App</div>
<div class="app"></div>
<div class="app"></div>
<div class="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
</html>
Upvotes: 3