02 Components
Last time, for our button counter, we saw a dynamic component (component.dynamic) that re-renders itself when the slice of the model in the store it listens to changes. We’re going to go over a couple more common types of components here (and we’ll revisit the last few types a few tutorials from now). For a more comprehensive overview of all components, visit the components module from the sidebar.
To avoid having to set the project up again, we’ll work from where we left off last time. Let’s update our imports first:
import gleam/int
import gleam/list
import lily/client
import lily/component.{type Component}
import lily/event
import lily/store
import lustre/element.{type Element}
import lustre/element/html
We’re going to make another toy app that allows us to create different items, numbered by id, in a list and then remove the most recent item that was created. This means that we’ll need to update our model so that it holds the next id we’re giving onto the list item and a list of all the existing items.
pub type Model {
Model(next_id: Int, items: List(Int))
}
We also will now have two different Message constructors, one for adding list items and one for removing the oldest item:
pub type Message {
Add
Remove
}
We’ll also need to update our update function. When we receive an Add message, we should increment next_id and prepend a new item to the list. On the other hand, when we receive a Remove message, we’ll need to drop the latest item on the list:
fn update(model: Model, message: Message) -> Model {
case message {
Add ->
Model(next_id: model.next_id + 1, items: [model.next_id, ..model.items])
Remove -> Model(..model, items: list.drop(model.items, 1))
}
}
We’ll also now need new view functions for mounting our components. To make break up a larger view function consisting of multiple components that we will put into our component.mount. Since we’ll need to need multiple components – the buttons for adding and removing, and the list itself, at the very list, we can wrap multiple components using component.fragment. Add this as a new view function:
fn view(_model: Model) -> Component(Model, Message, Element(Message)) {
component.fragment([
component.static(fn(_nest) { html.h1([], [html.text("Components")]) }),
buttons(),
rows(),
])
}
component.fragment takes a list of components. We’re going to first add a static component, which renders once and doesn’t update on its own, no matter what happens to the server. component.static takes an argument in the form of fn(nest), which returns whatever you run pass as argument into your to_html under component.mount. Apart from component.fragment, nest is how you pass child components into specific places within the HTML markup of a parent component. If the parent component simply calls the child’s render function, the child component would just be part of the parent’s HTML. This means that Lily will not have a separate component to watch, so the child wouldn’t be able to re-render alone. For our static component of the title, we’re not nesting any other component inside, so it’s just an exact function that returns HTML markup inside only.
Now, let’s look at a case where we actually need to use nest. For our buttons, we’ll need to have two button components inside for us to attach our event.on_click function to. This means that we’ll use nest within another static component. Your nested component will have its own rendering rules, meaning that if you nest a dynamic component within a static one, the rest of the static component outside the nested child components won’t ever re-render, whereas the dynamic component itself can. Whenever you want to add a nested component inside another, unless you are using component.fragment, you’ll probably need to use nest. Have a look back over component.mount to see how we defined the nest function when using Lustre for HTML templating. We can do the exact same for HTML strings. Right now, we’re going to be using nest to add two buttons within a static div:
fn button(
label: String,
message: Message,
) -> Component(Model, Message, Element(Message)) {
component.static(fn(_nest) { html.button([], [html.text(label)]) })
|> event.on_click(message: message)
}
fn buttons() -> Component(Model, Message, Element(Message)) {
component.static(fn(nest) {
html.div([], [nest(button("Add", Add)), nest(button("Remove", Remove))])
})
}
Here, we see how having more modular and lightweight components can help in re-using component code. Whereas our button is a fairly straightforward static component in this case, for more complex once with multiple events and configurations, we can write various functions returning a Component and use these definitions in different ways.
Now, let’s move to the list itself. While we can also write a dynamic component that maps over a list-based slice of the model to generate HTML markup, this means that the entire list is rendered every single time we want to add new elements in. While this is fine for many cases, especially shorter lists that rarely change, for longer lists with more frequent updates, re-ordering, or rows with inputs/focus/animations, Lily provides component.each for you. component.each, like component.dynamic, takes the slice of the model, which must be a List(ItemType). The second argument is the key, which extracts an identifiable key from ItemType, in other words fn(ItemType) -> ItemId. The final argument is once again the render function, but on top of needing a nest, it also needs the original item, in other words the function it expects is fn(item: ItemType, nest) -> html. To make this more concrete, let’s look at our rows() function:
fn rows() -> Component(Model, Message, Element(Message)) {
component.each(
slice: fn(model: Model) { model.items },
key: fn(id) { id },
render: fn(id, nest) {
nest(
component.static(fn(_nest) {
html.p([], [html.text("Item #" <> int.to_string(id))])
})
|> component.transition(enter: "item-enter", exit: "item-exit"),
)
},
)
}
Here, you can see that we’re taking our list defined earlier within our new model as the slice, with the list contents becoming the keys for each. When we’re then rendering, to now put a static component that we can apply a transition to, we’re going to use nest again. While this example could very well be made without nesting and having just HTML markup, we’re going to use it to demonstrate how we can add exit animations to HTML elements that are being destroyed/removed. For items not needing an enter animation, just leave the animation class as an empty string. As you can see, we’re using "item-enter" for our enter animation and "item-exit" for our exit animation, meaning that we’ll need to add some CSS styles to the head of our index.html:
<style>
.item-enter { animation: item-in 300ms; }
.item-exit { animation: item-out 300ms forwards; }
@keyframes item-in { from { opacity: 0; transform: translateX(-1em); } }
@keyframes item-out { to { opacity: 0; transform: translateX(1em); } }
@keyframes item-fade { to { opacity: 0; } }
@media (prefers-reduced-motion: reduce) {
.item-enter { animation: none; }
.item-exit { animation: item-fade 150ms forwards; }
}
</style>
Let’s finish up by updating our main function:
pub fn main() {
store.new(init: Model(next_id: 1, items: []), update:)
|> client.start
|> component.mount(
selector: "#app",
to_html: element.to_string,
to_placeholder: fn() { element.element("lily-nest", [], []) },
view: view,
)
}
Now, run the shell script we set up last time to serve the project again and you should be able to see the results in localhost:1234!
Check out the /examples folder in the GitHub repo for a copy of this example under /examples/02-components.