#dynamic attributes
4 messages · Page 1 of 1 (latest)
Hi @tight solstice. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Astro, you can use local variables in curly braces to pass attribute values to both HTML elements and components. Here's an example:
---const name = "Astro";---
<h1 class={name}>Attribute expressions are supported</h1>
<MyComponent templateLiteralNameAttribute={`MyNameIs${name}`} />
In this example, the name variable is used to dynamically set the class of an h1 element and an attribute of a custom component.
However, it's important to note that HTML attributes will be converted to strings, so it's not possible to pass functions and objects to HTML elements. For example, you can’t assign an event handler to an HTML element in an Astro component. Instead, you should use a client-side script to add the event handler, like you would in vanilla JavaScript:
<button id="button">Click Me</button>
<script>
function handleClick () {
console.log("button clicked!");
}
document.getElementById("button").addEventListener("click", handleClick);
</script>
In this example, the handleClick function is defined in a client-side script and added as an event listener to a button element.
For conditional rendering of attributes, you can use JavaScript expressions. For example, if you want to conditionally add an aria-current attribute, you can do something like this:
aria-current={current === '/' ? 'page' : undefined}
In this example, the aria-current attribute is set to 'page' if current equals '/', otherwise it's set to undefined which effectively omits the attribute.
Please note that dynamically-injected attributes aren’t supported in React or Svelte, and the same applies to Astro for consistency.