Skip to main content

useAttrs

The useAttrs hook allows components to access attributes passed from their parent, excluding props. This is useful for forwarding extra attributes like classes, data attributes, and event listeners.

Syntax

<MyComponent class="red" data-info="example">
<p>Hello</p>
</MyComponent>

Inside MyComponent, useAttrs() will return:

const attrs = useAttrs();
console.log(attrs); // { class: "red", "data-info": "example" }

Use Case

Example of Attribute Forwarding

<component :style="{ color: 'red' }">
<p>This component inherits passed attributes</p>
</component>
const { useAttrs } = DOMY;

const Component = DOMY.createComponent({
html: `
<div d-attrs="attrs">
<template d-insert="$childrens[0]"></template>
</div>
`,
app: () => {
const attrs = useAttrs();
return {
attrs
};
}
});

The useAttrs() hook will have the value { style: 'color:red' }.

Example with Props

Let's imagine count is a prop of the ErrorMessage component:

<ErrorMessage class="warning" :count="5">
<p>Error occurred</p>
</ErrorMessage>

Inside ErrorMessage, we will have:

const attrs = useAttrs();
console.log(attrs); // { class: "warning" }