Skip to content
Advertisement

Open one accordion section at a time. (Svelte)

I’d like to ask someone who can figure out how to allow this accordion component to open only one section at a time.

It means that if a new accordion is open the previous one has to close automatically.

In the ideal situation, this function could be optional for specific accordions.

Thank you for your time.

Accordion.svelte

JavaScript

app.svelte

JavaScript

Advertisement

Answer

For this one would usually use a context. The context can then manage the current accordion (or a key representing it) or dispatch events to other accordion instances.

As an example of storing the current accordion:

JavaScript

If there is no wrapper component that is used in conjunction with the accordion items, a context has be created elsewhere (e.g. the App). Also, each accordion item should also create its own context, so if it contains items of its own, it will not be closed if a child is opened.

When an accordion is opened the current accordion of the context can be updated. A reactive statement can be used to close all other accordions that belong to a context.

JavaScript

REPL example

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement