9

In __layout file I want to pass one variable lets say btnclicked="HR",and I want to collect same in the component which is rendered in Slot ? how to do it pls help ?

ajay dalwani
  • 99
  • 1
  • 2

1 Answers1

2

If you want to pass data that will be reactive, then I think the way to do it is to use a Svelte store with Context.

// in __layout.svelte
  <script>
    import { setContext } from 'svelte';
    import { writable } from 'svelte/store';

    const btnClicked = writable('');

    setContext('btnClicked', btnClicked);

    //...some code that sets the btnClicked store value
  </script>

  <slot />

// in child.svelte
  <script>
    import { getContext } from 'svelte';

    const btnClicked = getContext('btnClicked');

    // use $btnClicked in this component to access the value
  </script>
EvanMorrison
  • 1,212
  • 8
  • 13
  • Use of the Context API is more appropriate for situations where you (a) have many child components and do not wish to pass props to every single one or (b) have a deeply nested component hierarchy where passing props could be prone to error. See [Context API](https://svelte.dev/tutorial/context-api) on the Svelte site. – vhs Feb 21 '22 at 06:31
  • What's your point here @vhs? Do you have a solution to the question that doesn't use the Context API? I would be happy to hear it. But in the scenario described by OP you cannot simply pass props in the usual fashion from parent to child. – EvanMorrison Feb 22 '22 at 18:03
  • 1
    As it stands there isn't enough information to answer the question and Context API is an advanced use case which isn't something I'd encourage users to jump into unless they have the ability to describe their own problems adequately. – vhs Feb 23 '22 at 08:36
  • 1
    Respectfully, I disagree. If you're familiar with SvelteKit and the api for `__layout.svelte` files specifically, then there is sufficient information to answer the question, which I did. IMO, the Svelte Context API is readily accessible and there's nothing particularly advanced or dangerous about using it. – EvanMorrison Feb 26 '22 at 07:57
  • Maybe I am missing something here, but why not simply have the store in a separate .js file and import it in both files? – Nicolas Le Thierry d'Ennequin May 14 '22 at 05:52
  • can you go the other way from child to __layout? – chovy Jun 02 '22 at 04:38