DEV Community

Cover image for Recursive components
Florian Klenk
Florian Klenk

Posted on

Recursive components

Given the recursive structure of my project I have to render the Category multiple times calling itself.
Fortunately in svelte that is not a problem.
My component file is called category.svelte and the only thing I need to do is importing category.svelte from within category.svelte again. I named the component CategoryComponentRecursive as you can see below.

<script lang="ts">
  import * as Card from '$lib/components/ui/card';
  import CategoryComponentRecursive from './category.svelte';
  import type { Category } from '../schemas/category';
  let { category }: { category: Category } = $props();
</script>

<Card.Root>
  <Card.Header>
    <Card.Title>{category.name}</Card.Title>
  </Card.Header>
  <Card.Content>
    {#each category.categories as childCategory}
      <CategoryComponentRecursive category={childCategory} />
    {/each}
  </Card.Content>
</Card.Root>
Enter fullscreen mode Exit fullscreen mode

I have a category component which is a shadcn svelte card and this calls itself if child categories where detected.
You can look up the category component in the repo.

Top comments (0)