List Rendering
Render arrays with the List component
The List component allows you to map over an array render an element/component for each item in the array.
List
List takes two props:
each- the array to renderas- a function that receives each item and returns JSX
The as function gets called with a single parameter - a function which when called returns the value of the item.
import { reactive } from 'hydroxide'; import { List } from 'hydroxide-dom'; function NameList() { const names = reactive(['Cooper', 'Charlie', 'Gus', 'Oliver']); return ( <ul> <List each={names()} as={name => <li >{name()}</li>} /> </ul> ); } export default NameList;
List.Indexed
List does not provide the index as second parameter for performance reasons.
When you need the index as well as the item value, use List.Indexed instead of List.
The as function gets called with two parameters - item function and index function
import { reactive } from "hydroxide"; import { List } from "hydroxide-dom"; function TodoApp() { const input = reactive(""); const todos = reactive([ { task: "Learn Hydroxide", done: false }, { task: "Build something", done: true }, { task: "Ship it", done: false }, ]); function toggleDone(index) { todos(index, "done").do((done) => !done); } function removeTodo(index) { todos.remove(index); } function addNewTask() { if (input() === "") return; todos.push({ task: input(), done: false }); input.set(""); } function handleKeyDown(e) { if (e.key === "Enter") { addNewTask(); } } return ( <div class="app"> <div class="input-container"> <input type="text" bind-value={input} on-keydown={handleKeyDown} placeholder="Create Task" /> <button class="primary-button" on-click={addNewTask}> Add </button> </div> <ul> <List.Indexed each={todos()} as={(todo, index) => ( <li class={todo().done ? "done" : ""}> <span class="task">{todo().task}</span> <button class="toggle" on-click={() => toggleDone(index())}> {todo().done ? "✓" : "○"} </button> <button class="remove" on-click={() => removeTodo(index())}> X </button> </li> )} /> </ul> </div> ); } export default TodoApp;