Skip to content

Instantly share code, notes, and snippets.

@nk4dev
Last active February 2, 2023 05:21
Show Gist options
  • Save nk4dev/02f108b9aecb9839d06f9048e45d22db to your computer and use it in GitHub Desktop.
Save nk4dev/02f108b9aecb9839d06f9048e45d22db to your computer and use it in GitHub Desktop.
single code React on html.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>React jsx-esm-standalone</title>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- @babel/standaloneでESModuleを利用するために、data-type="module"を追加 -->
<script type="text/babel" data-type="module">
// CDN経由でReactを読み込む(ESModuleであればブラウザから直接利用可能)
import React, {useEffect , useState } from "https://cdn.skypack.dev/react";
import ReactDOM from "https://cdn.skypack.dev/react-dom ";
const getWindowSize = () => {
const [windowSize, setWindowSize] = useState({
width: 0,
height: 0,
});
useEffect(() => {
if (typeof window !== "undefined") {
const handleResize = () => {
setWindowSize({
width:
window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener("resize", handleResize);
handleResize();
return () => window.removeEventListener("resize", handleResize);
} else {
return;
}
}, []);
return windowSize;
};
const Counter = () => {
const { height, width } = getWindowSize();
return (
<>
<div>
<h1>aaa</h1>
<h1>{height}</h1>
<h1>{width}</h1>
</div>
</>
);
};
ReactDOM.render(<Counter />, document.getElementById('app'));
</script>
</head>
<body>
<div id="app"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment