Running React on the Client
Vals can also be used to host client-side code!
The server response includes a script referencing the client val
pomdtr/react_example
export const server = (req) =>
new Response(
`<html>
<head>
<title>React Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<main id="root"></main>
<script type="module" src="https://esm.town/v/pomdtr/react_example_client"></script/>
</body>
</html>`,
{
headers: {
"Content-Type": "text/html",
},
},
);
JSX can be used in the client val thanks to this magic comment
pomdtr/react_example_client
/** @jsxImportSource https://esm.sh/react **/
Make sure to only import from esm.sh (npm: specifier are not supported in the browser)
pomdtr/react_example_client
import React from "https://esm.sh/react";
import ReactDOM from "https://esm.sh/react-dom";
function Counter() {
const [counter, setCounter] = React.useState(0);
return (
<div>
<span>{counter}</span>
<div>
<button onClick={() => setCounter(count => count - 1)}>-</button>
<button onClick={() => setCounter(count => count + 1)}>+</button>
</div>
</div>
);
}
export function App() {
return (
<>
<h1>React Example</h1>
<Counter />
</>
);
}
The app will be rendered inside the root div
pomdtr/react_example_client
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
Additional resources: