Docs

Everything You Need to Know

Components

Intro

Components are magical unicorns. They take data and turn it into your app. ChocolateChip-UI's components are very versitile. You can create a component with nothing but an element and add functionality later. Or you can configure it all at once.

A component's data binding is one-directional, making it easy to reason about. After modifying your data, just render the component. If you define your component to use a State object, whenever you modify the state, the component will re-render automatically.

When you create a component, you can define its template using an ES6 template literal or our special tagged template literal: html``. As of version 5.2.0, you can also use JSX. If you need to, you can even change the component's template later using the .setTemplate(template) method. Here's a component with its render method returning a template literal:

const myComp = new Component({
  element: '#list',
  // Define template in render function:
  render: (data) => html`
    <li>${ data }</li>`
})
myComp.render('This is some data!')
          

You can also define actions for a component. Actions let you capture user interactions. If the events are targeting the element's descendants, they will be delegated on the element.

By default, ChocolateChip-UI encodes any HTML or JavaScript in the data before rendering it in a component. You can tell a component to render data unencoded, but you should only do this with data you can trust. Automatic encoding helps prevent injection of malicious scripts in your document. To render data unencryptic, put an exclamation point before the ${:

const myComp = new Component({
  element: 'list',
  // Use "!" to render data unescaped:
  render: (person) => html`
    <li$gt;!${ person.name }</li>`
})
          

You create an instance of a component with the new Component() method:

const luminariesComponent = new Component({
  element: '#repeaterWithImages', 
  state: luminariesComponent,
  render: (person) => html`
    <li>
      <img src='${ person.image }' alt=''>
      <div>
        <h3>
          ${ person.firstName } ${ person.lastName }
        </h3>
      </div>
    </li>`,
  actions: {
    element: 'li',
    event: 'tap',
    callback: function() {
      console.log($(this).text());
    }
  }
})