Skip to content

Instantly share code, notes, and snippets.

@gaearon
Last active February 6, 2023 06:37
Embed
What would you like to do?
Multiple React components on a single HTML page
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</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@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked comment number ' + this.props.commentID;
}
return e(
'button',
{ onClick: () => this.setState({ liked: 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);
const root = ReactDOM.createRoot(domContainer);
root.render(
e(LikeButton, { commentID: commentID })
);
});
@christian-go3
Copy link

Cool!

@Chrissiku
Copy link

Amazing

@Meet-7777
Copy link

Can we use functions instead of classes to load components?

@lxxxxx-oss
Copy link

帅的呀~

@AndyIsAMan
Copy link

Thanks very much!

@AndyIsAMan
Copy link

AndyIsAMan commented Aug 28, 2022

root.render(e(LikeButton)); this line i am not understand

@RicoShen
Copy link

RicoShen commented Sep 7, 2022

root.render(e(LikeButton)); this line i am not understand

@wuddy233
Copy link

谢谢你

@creativoloco
Copy link

I had no idea it was possible to have as many root elements as you want. Could be considered as bad practice? Does it matter?

@MahdiSohaily
Copy link

It seems to be great.

@DarrenSem
Copy link

root.render(e(LikeButton)); this line i am not understand

Read the .js file that sets alias "e" to "React.createElement"

@0rigin-c0de
Copy link

awesome

@cc-ww
Copy link

cc-ww commented Feb 6, 2023

so niubility

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment