Created
June 4, 2024 05:43
-
-
Save cassidoo/c1d4390be8ba9755d93227bca49def25 to your computer and use it in GitHub Desktop.
Astro web component for a random post from a list of slugs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
let { text, posts } = Astro.props; | |
--- | |
<astro-link data-posts={posts}> | |
<a>{text}</a> | |
</astro-link> | |
<script> | |
class AstroLink extends HTMLElement { | |
constructor() { | |
super(); | |
function randomPost(slugs) { | |
slugs = slugs.split(","); | |
const randomSlug = slugs[Math.floor(Math.random() * slugs.length)]; | |
return `/post/${randomSlug}`; | |
} | |
const slugs = this.dataset.posts; | |
const link = this.querySelector("a"); | |
link.href = randomPost(slugs); | |
} | |
} | |
customElements.define("astro-link", AstroLink); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment