Write, Run & Share Preact code online using OneCompiler's Preact online editor for free. Pick 'Preact' as the language and you get a small working component to start from. The preview updates as you type, so there's nothing to install or build.
Preact is a tiny alternative to React with the same modern API: components, hooks, and a virtual DOM. Most React code works in Preact with little or no change, and the library itself is only a few kilobytes, which makes it popular for widgets, embedded apps and pages where load time matters.
The editor loads Preact together with htm, which lets you write JSX-like markup inside tagged template strings. No compiler is needed.
import { html, render, useState } from 'https://esm.sh/htm@3/preact/standalone';
A component is a function that returns markup. Interpolate values and other components with ${...}.
function Greeting({ name }) {
return html`<h1>Hello, ${name}!</h1>`;
}
render(html`<${Greeting} name="Preact" />`, document.getElementById('app'));
useState works the same way as in React.
function Counter() {
const [count, setCount] = useState(0);
return html`<button onClick=${() => setCount(count + 1)}>Count: ${count}</button>`;
}
Map an array to markup. Give each item a key so Preact can track it between renders.
const fruits = ['Apple', 'Banana', 'Cherry'];
function FruitList() {
return html`
<ul>
${fruits.map((fruit) => html`<li key=${fruit}>${fruit}</li>`)}
</ul>
`;
}
useEffect runs after render. Return a function to clean up.
import { html, render, useState, useEffect } from 'https://esm.sh/htm@3/preact/standalone';
function Clock() {
const [time, setTime] = useState(new Date());
useEffect(() => {
const id = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(id);
}, []);
return html`<p>${time.toLocaleTimeString()}</p>`;
}