CaptainCodeman / svelte-headlessui

HeadlessUI components for Svelte
https://captaincodeman.github.io/svelte-headlessui/
MIT License
554 stars 25 forks source link

Disclosure: How to iterate over a list of options? #24

Closed rohanrajpal closed 1 year ago

rohanrajpal commented 1 year ago

Thanks a ton for this beautiful library! I had one small doubt.

Say I have the list of options

const content = [
        {
            title: '1. Is your Instagram page a business or a creator account?',
            description:
                "Here's how you can confirm whether your Instagram page is a business or a cretor account ->",
        },
        {
            title: '2. Is your Instagram page connected to a Facebook page?',
            description:
                "Here's how you can confirm whether your Instagram page is connected to a Facebook page ->",
        },
        {
            title: '3.Turn on "Allow Messages" setting',
            description: 'Here’s how you can toggle the “Allow Messages” setting ->',
        },
    ];

How do I iterate over these and create a disclosure?

The following code doesn't work since one cant just iterate over an array of stores I guess (or maybe i'm not smart enough to figure out how)


<script lang="ts">
// .. define content like above
 const contentStores = 
        content.map((item) => {
            return createDisclosure({ label: item.title, expanded: false });
        }),
</script>

{#each $contentStores as store, idx}
            <DownArrow class="h-6 w-6 {$store.expanded ? 'rotate-180' : ''}" />
            // Error: Stores must be declared at the top level of the component (this may change in a future version of Svelte)
{/each}
CaptainCodeman commented 1 year ago

You could create a child component and use it in the {#each} block, that makes it easy for each one to have it's own disclosure instance. Here's an unstyled example:

https://svelte.dev/repl/3add15ebfc244604ba5c09d6bc65dac0?version=3.55.0

You might also remove the numbers from the content and use the index from the each block, so they are always consistent.

rohanrajpal commented 1 year ago

Neat trick! Thanks, this should work for me.