Skip to content

Latest commit

 

History

History
114 lines (81 loc) · 2.51 KB

BauStateArray.md

File metadata and controls

114 lines (81 loc) · 2.51 KB

Observing Array

This guide describes how to display reative array.

Creation

Example of creating a state observing an array:

// Empty initial state
const todosState = bau.state([]);

// Use initial state
const initialState = [{ label: "a1" }, { label: "b1" }];
const todosState = bau.state(initialState);

Mutation

They can use several operations to mutate the array, simply use the standard javascript array operations on todosState.val. The val property contains the array to mutate.

  1. Append an item at the end: push
todosState.val.push({ label: "my-label" });
todosState.val.push({ label: "my-label" }, { label: "other-label" });
  1. Remove the last item: pop
todosState.val.pop();
  1. Prepend an item at the begining: unshift
todosState.val.unshift({ label: "my-label" });
todosState.val.unshift({ label: "my-label" }, { label: "other-label" });
  1. Remove the first element: shift
todosState.val.shift();
  1. Splice the array: Remove one or more item from an index, and eventually add some items at the index
// Remove the third element
todosState.val.splice(2, 1);

Render List

Render with ul and li

To display a list of items, use the javascript map on myArray.val

const TestBindArrayUL = () => {
  const arrayState = bau.state<string[]>([]);
  const inputEl = input({ focus: true, placeholder: "Enter text" });
  const renderItem = (value: string, index?: number) =>
    li(`${index} ${value} `);

  const onclick = () => {
    arrayState.val.push(inputEl.value);
    inputEl.value = "";
  };

  return article(
    h1("Loop Array with ul li"),
    inputEl,
    button({ onclick }, "Add"),
    bau.loop(arrayState, ul(), renderItem)
  );
};

Render with tbody, tr, and td

Here is an example of displaying an array with table, tbody, tr and td:

const TestBindArrayTable = () => {
  const arrayState = bau.state<string[]>([]);

  const inputEl = input({ focus: true, placeholder: "Enter text" });
  const onclick = () => {
    arrayState.val.push(inputEl.value);
    inputEl.value = "";
  };

  const renderItem = (value: any, index?: number) => tr(td(index), td(value));

  return article(
    h1("Array with table, tbody, tr, and td"),
    inputEl,
    button({ onclick }, "Add"),
    table(bau.loop(arrayState, tbody(), renderItem))
  );
};

Examples

Check out our examples to observe and display array of data: