Skip to content
Manolo Edge edited this page Oct 28, 2023 · 3 revisions

Cardboard offers a set of methods for adding logic to your apps. Some logic is handled in the tag, and some logic is handled using the functions mentioned on this page, like each.

Tag Logic

Tag logic allows you to do things such as hiding, disabling, adding classes, styles, etc... in a reactive way.

const myElement = tag('div');
const isActive = state(true);

myElement.classIf(isActive, ['active', 'highlighted']);
myElement.hideIf(isActive);

See Manipulating Tags for a more detailed explanation.

Each

Documentation

When building interfaces you will often need to work with lists of data. So instead of having to manually add each item, you can use the each function to do the job for you.

each can work with a good old array, or with a Consumable<any[]>. If you provide a Consumable, the list will update whenever the Consumable changes.

Static list

Let's look at the very simplest example, a static list, that will not change:

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

div(
    each(colors, (color) => 
        button(color).addStyle('color', color)
    )
);

This code will add a button for each color to the div. Note that if you change the colors array, the rendered content will stay the same. To update the content, you can by creating a dynamic list.

Dynamic list

If you want the content to update when the content changes, you must provide an array Consumable (created with state in the example below). By doing this, whenever the colors state changes, the content will be updated accordingly.

You can also use listState for better ergonomics.

Take a look at this example:

const colors = state(['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']);
const selectedColor = state('red');

div(
    each(colors, (color) => 
        button(color)
          .addStyle('color', color)
          .stylesIf(equalTo(selectedColor, color), { fontWeight: 'bold' });
    )
);

There are a couple of differences with the static example:

  • On one hand we create a state (aka Consumable) instead of a regular array.
  • We create another state for the selected color.
  • This allows us to use logic like stylesIf in this case. We specify that, when the color is equal to the selectedColor, the text must be bold. This will happen each time the selected color is changed.

This is quite handy, we can then modify the colors, set the selectedColor, remove colors, etc...

You can add items to colors.value yourself, but note that using push and other methods will not work, you must assign a new value. Gladly Cardboard offers a few methods to handle this a bit better. So instead of having to do this:

colors.value = [...colors.value, newColor];

We can do this:

stateAdd(colors, 'black');

Take a look at the State Utilities page for more information.