Skip to content

Instantly share code, notes, and snippets.

@tbreuss
Last active December 17, 2023 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbreuss/ef49e714f2572e081f4c176fd7125dff to your computer and use it in GitHub Desktop.
Save tbreuss/ef49e714f2572e081f4c176fd7125dff to your computer and use it in GitHub Desktop.
Simple ivi.js example with nested components using context
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ivi example</title>
</head>
<body>
<script type="module">
import {createRoot, update, component, useState, context} from 'https://cdn.jsdelivr.net/npm/ivi@3.0.2/+esm'
import {htm} from 'https://cdn.jsdelivr.net/npm/@ivi/htm@3.0.2/+esm';
const [getCountContext, CountContext] = context();
const Counter = component((c) => {
const init = getCountContext(c) || 0;
const [count, setCount] = useState(c, init);
const dec = () => {
setCount(count() - 1);
};
const inc = () => {
setCount(count() + 1);
};
return () => {
return htm`
<div class="clicker">
<div>${count()}</div>
<button @click=${dec}>-</button>
<button @click=${inc}>+</button>
</div>
`};
});
const App = component(() => () => htm`
<div class="app">
${CountContext(33, Counter())}
${CountContext(44, Counter())}
${CountContext(55, Counter())}
${CountContext(66, Counter())}
</div>
`
);
update(createRoot(document.body), App());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment