Todo list With JSX Web Components
A first full app with Dim: define, Dim’s own html tagged templates, hooks, and .props. If you are new to Dim, start with Getting Started.
We will build a todo list using functional web components — hooks for state, useScope for composition, and .props for passing functions between elements.
Refresher
If you are familiar with React, these hooks should feel familiar:
-
useState: Is a hook that allows us to manage state in the component. It returns an array with the current state and a function to update the state. We can also pass an initial value to the state. It works similarly to React'suseState. -
useEffect: Is a hook that allows us to run side effects in the component. It takes a function and an array of dependencies. If the dependencies change, the function will be called again. This is a way to run side effects in the component. -
useStyle: Is a hook that allows us to add styles to the component. It takes a CSS template literal and adds it to the shadow DOM of the component. This is a way to encapsulate styles to the component. -
useMemo: Is a hook that allows us to memoize the result of a function. It takes a function and an array of dependencies. If the dependencies change, the function will be called again. This is a way to optimize the rendering of the component. -
useScope: Is a hook that allows us to introduce components to the scope of the component. This is a way to share components between components. -
Rendering: Rendering is done by Dim's own
htmltagged templates (implemented insrc/core/renderer). Parts update values in place so focus, selection, and child custom-element state survive re-renders. -
define(): Is a function that allows us to define a web component. It takes an object with the tag name of the component, the functional component itself and any dependencies that should be shared down the component render tree.
Note: While we have props described in a similar way to react, dim functional components also have a second argument, which contains all the shared dependencies. This is being investigated to see if this is a funtional way of introducing shared dependencies to web components. This allows us to share state and other dependencies between components. (The theory is, by doing this, we can serialize functions to strings in a way that we can then use for something like vanillaJS module federation.)
Todo List component
Lets start by creating a simple todo list web component. We will create a todo list component that will render a list of todos. We will use what we created in the previous article to render the todo list.
We can start by creating a simple todo list component.
const { define } = Dim;
const Todo = (props, { html }) => {
return html`
<div>
<h1>Todo App</h1>
</div>
`;
};
define({ tag: "todo-app", component: Todo });
In this example we are creating a simple web component after loading the CDN IIFE (window.Dim). We render a div with an h1. define sets the tag name; html comes from the component’s second argument (Dim’s own renderer).
Input Form
Now lets create an input form to add todos to the list. We will use what we created in the previous article to manage the state of the input form.
const AddItemForm = ({ onAdd }, { useState, useStyle, html, css }) => {
console.log("AddItemForm", onAdd);
const [inputValue, setInputValue] = useState("");
useStyle(css`
button {
background-color: #029cfd;
border: none;
border-radius: 5px;
color: white;
padding: 5px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
cursor: pointer;
}
`);
const handleInput = (e) => {
e.preventDefault();
setInputValue(e.target.value);
};
const clearInput = () => {
setInputValue("");
};
const addTodo = () => {
onAdd(inputValue);
clearInput();
};
return html`
<input
type="text"
placeholder="Add todo"
.value="${inputValue}"
@change="${handleInput}"
/>
<button @click="${addTodo}">Add</button>
<button @click="${clearInput}">Clear</button>
`;
};
export default AddItemForm;
In this example we are creating an input form to add todos to the list. We use the useState hook to manage the state of the input form and the useStyle hook to add styles to the component. We render an input field and two buttons. Event listeners are added to the input field and buttons to handle user input.
Lets add the AddItemForm into the todo list component. We can update the file like the following:
const { define } = Dim;
const Todo = ({}, { useState, useStyle, useMemo, useScope, html, css }) => {
useScope({
'add-item-form': AddItemForm
});
const [todos, setTodos] = useState([]);
const numberOfTodoItems = useMemo(() => {
console.log("memo calculation triggered");
return todos.length;
}, [todos]);
const addTodo = (todo) => {
setTodos([...todos, todo]);
};
return html`
<div>
<h1>Todo App</h1>
<add-item-form .props="${{addTodo}}"></add-item-form>
<p>Number of todo items: ${numberOfTodoItems}</p>
</div>
`;
};
define({ tag: "todo-app", component: Todo });
Lets breakdown whats going on:
-
Hooks and
html/csscome from the second argument of the component (injected bydefineafter the CDN script loads). -
useScope: This is a hook that allows us to introduce other dim components to the scope of the component. This is a way to create reusable web components.
-
useMemo: This is a hook that allows us to memoize the result of a function. It takes a function and an array of dependencies. If the dependencies change, The function will be called again. This is a way to optimize the rendering of the component. In this example it is used to calculate the number of todo items. If the todos change, the function will be called again. in a "real-world" example, this could be used to do more heavier calculations.
-
addTodo: A function that will add a todo to the list. It takes a todo as an argument and adds it to the list of todos. This should work like you would expect in ReactJS.
Note: After useScope, the child tag is available in the template. We pass the addTodo function via .props — HTML attributes cannot carry functions. Dim watches .props on the host and re-renders when it changes. Prefer .props for objects and callbacks; use attributes for primitives and JSON. See Props & attributes.
The Todo list
Now lets create a list of todos.
import ListItem from "./ListItem.js";
const TodoList = ({ todos, onRemove }, { useScope, useEffect, html }) => {
console.log("todo list render", todos);
useScope({
"list-item": ListItem,
});
useEffect(() => {
console.log("todos list updated");
}, [todos]);
return html`
<ul>
${todos.map((todo, index) => {
const handleRemove = () => {
onRemove(index);
};
return html`
<list-item
.props="${{ todo, onRemove: handleRemove }}"
></list-item>
`;
})}
</ul>
`;
};
export default TodoList;
Lets break it down:
-
.props: we are passing the todos and onRemove function as props to the component. -
useScope: This is a hook that allows us to introduce other dim components to the scope of the component. This is a way to create reusable web components. -
useEffect: This is a hook that allows us to run side effects in the component. It takes a function and an array of dependencies. If the dependencies change, the function will be called again. In this example, it is used to log when the todos change. -
rendering: We are rendering a list of todos. We can use the Array map function to render a list of todos. We are also passing the todo and onRemove function as props to the
list-itemcomponent. This is a way to pass data to the component. Notice that we are using the.propsattribute to pass the props to the component.
The Todo list item
Now lets create the todo list item.
const ListItem = ({ todo, onRemove }, { useEffect, html }) => {
useEffect(() => {
console.log("List item mounted");
return () => {
console.log("List item unmounted");
};
}, []);
return html`
<li>
${todo}
<button @click="${onRemove}">Remove</button>
</li>
`;
};
export default ListItem;
This component should now seem relatively simple, but lets break it down for clarity.
-
useEffect: This is a hook that allows us to run side effects in the component. It takes a function and an array of dependencies. If the dependencies change, the function will be called again. In this example, it is used to log when the component is mounted and unmounted. -
rendering: We are rendering a list item with a todo and a button to remove the todo. An event listener is added to the button to handle the remove event. The onRemove function is called when the button is clicked. This is a way to pass data to the component.
Putting it all together
Now lets introduce the todo list to the todo component.
const { define } = Dim;
const Todo = ({}, { useState, useStyle, useMemo, useScope, html, css }) => {
useScope({
"add-item-form": AddItemForm,
"todo-list": TodoList,
});
const [todos, setTodos] = useState([]);
const numberOfTodoItems = useMemo(() => {
console.log("memo calculation triggered");
return todos.length;
}, [todos]);
const addTodo = (todo) => {
setTodos([...todos, todo]);
};
const removeTodo = (index) => {
setTodos(todos.filter((_, i) => i !== index));
};
return html`
<div>
<h1>Todo App</h1>
<add-item-form .props="${{ addTodo }}"></add-item-form>
<p>Number of todo items: ${numberOfTodoItems}</p>
<todo-list .props="${{ todos, onRemove: removeTodo }}"></todo-list>
</div>
`;
};
define({ tag: "todo-app", component: Todo });
Lets break it down:
-
rendering: We are rendering the todo list component. We pass the todos and onRemove function as props to the component. This is a way to pass data to the component. we also pass a function to remove a todo-item from the list.
-
shared dependencies: its important to note the all the components down the tree will be able to use the hooks we define in the shared dependencies. you should note that useStyle and useEffect are in the dependencies, but unused in the todo component. you should take note of this when using the hooks in the components. Be sure to include the hooks you need if a component needs it to work correctly.
Future considerations
- Done: Dim owns its renderer (
src/core/renderer) —html/render/keyed/ focus preservation — with no Lit dependency at runtime. - We can serialize functions to strings in a way that we can use them in vanillaJS module federation. This would allow us to create a more modular web application. I would also like to see if we can create a way to share dependencies between components in a more functional way. This would allow us to create more reusable components.
- Further React-like template sugar (beyond JSON-only
attr={{}}and self-closing custom elements, which the Dim renderer already supports).
Conclusion
Im interested to hear what you think about this approach. I dont recomend using this approach to create any production ready applications. This is more of an experiment to see if we can create a more functional way of creating web components. I think its nearing a level for me to try refactoring some of my other work to use this approach. As i created the todo list, i found that it was a learning experience and i had to make some changes to the way. Im sure there are more changes that can be made to make it better. I would like to hear your thoughts on this approach and if you think it could be improved in any way.