Svelte · Middle · Question 52 of 75

How can a component expose methods to its parent?

<!-- Dialog.svelte -->
<script>
  let dialog;
  export function open() { dialog.showModal(); }
</script>
<dialog bind:this={dialog}>...</dialog>

<!-- Parent -->
<Dialog bind:this={d} />
<button onclick={() => d.open()}>Open</button>

Explanation

Exported functions and constants become the component's instance API. Prefer props for data flow and keep this for imperative actions.

Further reading

Problem with a question

Svelte · Middle · question 52

Test yourself

Take the Svelte · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz