December 22, 2022
Create a Headings Component for an Astro Project with Svelte
Display headings for each markdown post as links.
By Ross Robinoblog / svelte / astro
Heading tags are the standard way to structure markdown content. Astro makes it simple to to parse markdown out of the box, and handles mdx content with a first party mdx integration.
I enjoy using Svelte to create my components, Astro provides another first party Svelte integration to work with Svelte.
Here’s how I created a component to parse all of the headings from a file or a list of headings and display them as links (see above).
First, we will create a Headings.svelte component. We will want to use this in two different places, so we will build it with that flexibility in mind. We can pass in either an imported file, or just the headings from the file in a layout.
Each .md or .mdx file can be imported with a built in Astro method which we will implement in the next section. Imported files contain a variety of data points, we can utilize these two:
Each heading object contained in headings has the following keys among others that we can reference:
We can now use this in our markdown layouts by providing headings, or in another page by passing in the entire file through the file prop.
Here, we can create a layout for posts to display the headings from our markdown file.
Utilize this layout in our markdown file in src/pages/posts/:
You may want to display your headings as a preview outside of the page itself (example).
We can import our files from src/pages/posts into the page we want to display them using Astro’s glob method. Then we can pass a post into the Headings component to display the headings from that post.
Because Astro runs at build time, this Headings component will be sent to the client as HTML and CSS with no JavaScript.
I’ve really enjoyed using Astro to create this blog. The first party .mdx integration and Astro.glob make it easy to maintain my content. I’d recommend it to others creating static sites and wanting to author their pages in markdown.
Thanks for reading!…