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

What is an Element Attribute?

An element attribute is a key-value pair that you can add to any HTML element. For example, <my-element name="Ribhararnus"></my-element>.

You can learn more about it here 👉 MDN: HTML Attributes.

Render Dynamic Data from Attributes

Let’s add a new attribute to your custom element and render its value dynamically.

<custom-element name="hello-world">
  <element-attr name="name" type="string">anonymous</element-attr>
  <template>
    <strong>
      Hello world, my name is
      <slot name="@name"></slot>
      !
    </strong>
  </template>
</custom-element>

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

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

How does it work?

You define a new attribute using the <element-attr> tag. The name attribute specifies the name of the custom element’s attribute, and the type indicates the data type. Defining the data type is important (you can find supported types in the element-attr reference).

You can render the attribute’s value using the <slot> tag. The name attribute in <slot> corresponds to the attribute name, and the @ prefix is required to distinguish it from state.

You can also set a default or fallback value inside the <element-attr> tag. If the attribute is not defined, it will use the default value.

Isn’t Your Custom Element a Bit Boring?

Let’s add some excitement by exploring the fascinating world of reactivity using states.