/* sample-app.jsx: React components written in JavaScript with JSX. Free sample from 99helpers.com/file-types/jsx Browsers and Node.js can't run this file as it is: the must first be compiled into ordinary JavaScript function calls. Set up: npm install react react-dom Run: npx tsx sample-app.jsx or bun sample-app.jsx Build: npx esbuild sample-app.jsx --jsx=automatic --bundle --platform=node --outfile=app.js npx babel sample-app.jsx --presets @babel/preset-react */ /** @jsxRuntime automatic */ // 1. Imports. The automatic JSX runtime adds its own import for the tags, // so React itself only needs importing for hooks like useState. import { useState } from "react"; import { renderToStaticMarkup } from "react-dom/server"; // 2. A component is a function whose name starts with a capital letter. // Its one argument, props, holds the attributes it was given. function Greeting({ name, lang = "en" }) { // 3. JSX looks like HTML, with differences: className instead of class, // htmlFor instead of for, and every tag must be closed (
). return (

{/* 4. Braces hold any JavaScript expression; this is a comment. */} {lang === "fr" ? "Bonjour" : "Hello"}, {name}!

); } // 5. Lists: map() an array to elements, each with a stable key. function Menu({ items }) { return ( ); } // 6. State and events: useState keeps a value between renders, and // onClick takes a function, not a string of code as in HTML. function LikeButton() { const [likes, setLikes] = useState(0); return ( ); } // 7. Composition and conditions: components inside components, a // fragment <>… to return several elements, and && to show // something only when a condition is true. function App({ items }) { return ( <> {items.length > 0 && } ); } const items = [ { id: "tea", name: "Thé vert", price: 3.5 }, { id: "cake", name: "Crème brûlée", price: 5.25 }, ]; // 8. Render. Here to an HTML string, so the file runs in a terminal; a // browser app calls createRoot(element).render() // from "react-dom/client" instead. console.log(renderToStaticMarkup());