#heading component

4 messages · Page 1 of 1 (latest)

maiden tangle
#

How can I make an Astro component for html headings with heading level as a typescript option?

daring pelicanBOT
#

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:

  1. Define a TypeScript Props interface in your Astro component. This interface should include the headingLevel and id as properties. The headingLevel will represent the heading level (1-6), and the id will be a string generated from the heading's text contents.
interface Props {
    headingLevel: number;
    id: string;
}
  1. Destructure the headingLevel and id from Astro.props in your component's frontmatter script.
const { headingLevel, id } = Astro.props;
  1. Use the headingLevel to dynamically create a heading element. You can use a template literal to create a string that represents the heading element, such as h1, h2, etc., based on the headingLevel. However, to avoid TypeScript errors, you need to cast this string to HTMLTag, which is a type provided by Astro.
import type { HTMLTag } from 'astro/types';
const HeadingElement = `h${headingLevel}` as HTMLTag;
  1. In your component's template, use the HeadingElement as a dynamic HTML tag. You can also use the id as 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.