Skip to content

Instantly share code, notes, and snippets.

@rachelnabors
Last active Oct 30, 2021
Embed
What would you like to do?
Adding multiple React components on a single HTML page
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add Multiple React components on a single HTML page</title>
</head>
<body>
<h2>Add Multiple React components on a single HTML page</h2>
<p>This page demonstrates using React with no build tooling to add multiple components to a single page.</p>
<p>React is loaded as a script tag.</p>
<p>
This is the first comment.
<!-- We will put our React component inside this div. -->
<div class="like_button_container" data-commentid="1"></div>
</p>
<p>
This is the second comment.
<!-- We will put our React component inside this div. -->
<div class="like_button_container" data-commentid="2"></div>
</p>
<p>
This is the third comment.
<!-- We will put our React component inside this div. -->
<div class="like_button_container" data-commentid="3"></div>
</p>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
'use strict';
function LikeButton(props) {
const [liked, setLiked] = React.useState(false);
if (liked) {
return 'You liked comment number ' + props.commentID;
}
return React.createElement(
'button',
{ onClick: () => setLiked(true) },
'Like'
);
}
// Find all DOM containers, and render Like buttons into them.
document.querySelectorAll('.like_button_container').forEach((domContainer) => {
// Read the comment ID from a data-* attribute.
const commentID = parseInt(domContainer.dataset.commentid, 10);
ReactDOM.render(
React.createElement(LikeButton, { commentID: commentID }),
domContainer
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment