dark IntroductionQuick StartRealm Mindset 01. Hello world02. Element Attributes03. Element States04. Element Flow05. Global States06. Data Bindings07. Children Rendering08. Custom Script Flow09. Reusability10. Dynamic Styles11. Events12. Conditional Rendering13. List Rendering14. HTTP Request15. The Dot Notation16. State Mutation17. Finale Server-side RenderingShadow DOM StylingASTRA StackPRO Stack
IntroductionQuick StartRealm Mindset 01. Hello world02. Element Attributes03. Element States04. Element Flow05. Global States06. Data Bindings07. Children Rendering08. Custom Script Flow09. Reusability10. Dynamic Styles11. Events12. Conditional Rendering13. List Rendering14. HTTP Request15. The Dot Notation16. State Mutation17. Finale Server-side RenderingShadow DOM StylingASTRA StackPRO Stack

Bringing Engagement with Element States

We promise to make our custom elements more engaging and exciting.

Element states in custom elements enable us to create dynamic and interactive elements. By defining and manipulating states, we can introduce responsiveness to user interactions, data changes, or any other events that impact the behavior or appearance of our custom element.

With states, we can track and update specific values within our custom element, triggering automatic re-rendering whenever a state changes. This reactivity empowers us to build dynamic user interfaces that respond in real-time, providing a more engaging and interactive experience for our users.

How to Define an Element State?

You can define an element’s state using the <element-state> tag. It’s similar to defining an element’s attribute (you can find supported types in the element-state reference).

<custom-element name="hello-world">
  <element-attr name="name" type="string">anonymous</element-attr>
  <element-state name="age" type="number">100</element-state>
  <template>
    <strong>
      Hello world, my name is
      <slot name="@name"></slot>
      !
    </strong>
    <em>
      and, I'll live until
      <slot name="#age"></slot>
      years old
    </em>
  </template>
</custom-element>

<div>
  <hello-world></hello-world>
</div>

<div>
  <hello-world name="R. Pracutian"></hello-world>
</div>
anonymous 100

To render the state’s value, use the <slot> tag with the state’s name, prefixed with a # symbol. The distinction between attributes and states is the prefix: attributes use the @ prefix, and states use the # prefix.

We apologize for promising reactivity earlier, but it hasn’t happened yet because our state is still static. Let’s take it a step further and introduce reactivity using the Element’s flow feature.