Attributes
You can retrieve attributes with the provided attr
method. It takes an attribute name and an optional default value and returns a VanJS State
object.
Example:
javascript
define("attributes-demo", ({ attr }) =>
p(
"Hello ",
attr(
"name", // attribute name
"Max" // optional default value
)
)
);
html
<attributes-demo name="Bob"></attributes-demo>
<attributes-demo name="Jimmy"></attributes-demo>
<!-- default value -->
<attributes-demo></attributes-demo>
Note
This method is a wrapper around van.state
. Because of this, you will need to use state derivation in places you want to be reactive.
js
define("not-reactive", ({ attr }) => p(`Hello ${attr("name").val}`));
define("very-reactive", ({ attr }) => p(() => `Hello ${attr("name").val}`));
Attribute reactivity
The State
obtained from attr()
is reactive to attribute change. This is useful when nesting Van Elements inside other Van Elements 🤯
javascript
define("reactive-attribute", ({ attr }) => p("Hello ", attr("name")));
define("attribute-parent", () => {
const name = van.state("John");
return p(
"Type your name: ",
input({
type: "text",
value: name,
oninput: (e) => (name.val = e.target.value),
}),
van.tags["reactive-attribute"]({ name }) // nested Van Element
);
});
html
<attribute-parent></attribute-parent>
Note
You can use kebab-case-attributes
.
js
const element = van.tags["some-element"]({ "data-text": "hello" });
Resulting HTML:
html
<some-element data-text="hello"></some-element>
However you cannot use camelCaseAttributes
🥺 it is not valid HTML syntax and will be turned into lowercase by the browser.