#heading component
4 messages · Page 1 of 1 (latest)
Hi @maiden tangle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
You can create an Astro component for HTML headings and use TypeScript to define the props that the component accepts. Here's a step-by-step guide based on the information provided in the extracts:
- Define a TypeScript
Propsinterface in your Astro component. This interface should include theheadingLevelandidas properties. TheheadingLevelwill represent the heading level (1-6), and theidwill be a string generated from the heading's text contents.
interface Props {
headingLevel: number;
id: string;
}
- Destructure the
headingLevelandidfromAstro.propsin your component's frontmatter script.
const { headingLevel, id } = Astro.props;
- Use the
headingLevelto dynamically create a heading element. You can use a template literal to create a string that represents the heading element, such ash1,h2, etc., based on theheadingLevel. However, to avoid TypeScript errors, you need to cast this string toHTMLTag, which is a type provided by Astro.
import type { HTMLTag } from 'astro/types';
const HeadingElement = `h${headingLevel}` as HTMLTag;
- In your component's template, use the
HeadingElementas a dynamic HTML tag. You can also use theidas an attribute for this element.
<HeadingElement id={id}>Your heading text here</HeadingElement>
Here's how the complete component might look:
---
import type { HTMLTag } from 'astro/types';
interface Props {
headingLevel: number;
id: string;
}
const { headingLevel, id } = Astro.props;
const HeadingElement = `h${headingLevel}` as HTMLTag;
---
<HeadingElement id={id}>Your heading text here</HeadingElement>
Remember to replace "Your heading text here" with the actual text you want to display in the heading.
Sources:
- Astro Components - Component Props (https://docs.astro.build/en/basics/astro-components#component-props)
- TypeScript - Component Props (https://docs.astro.build/en/guides/typescript#component-props)
- GitHub Issue - TS error for "id" attribute on dynamic HTML tag/component (https://github.com/withastro/astro/issues/8024)