How to get a reference to a Svelte component from within the component

Viewed 451

There's an easy way to get a reference to an instance of a sub component from the parent scope, as shown in the tutorial.

What I want is to get a reference to the component from within the component itself. So, if we were looking at the official Svelte demo linked above, I would be meaning that I want a reference to the InputField instance from within the InputField instance, rather than from App.svelte.

(The reason I want this: I need instances to fire hooks to external JS libraries that will interract with the instance programmatically.)

Copy of code from tutorial (for convenience and longevity)

App.svelte:

<script>
    import InputField from './InputField.svelte';
    let field;
</script>
<InputField bind:this={field}/>
<button on:click={() => field.focus()}>Focus field</button>

InputFiled.svelte:

<script>
    let input;
    export function focus() {
        input.focus();
    }

    // Somewhere here, I want a var, like you might imagine the following to do:
    let myself = this;
</script>
<input bind:this={input} />
2 Answers

You can get a refrence from the parent and pass it the child:

<script>
    import InputField from './InputField.svelte';
    let field;
</script>

<InputField bind:this={field} {field}/>

<button on:click={() => field.focus()}>Focus field</button>

once you get the field pass it to the input

<script>
    let input;
        export let field;
    export function focus() {
        input.focus();
    }
        let myself;
        $:if(field) myself = field;
</script>
<input bind:this={input} />

and you can use it with context.

When passing the reference that is set in the parent to the child as a prop it is possible to use it inside the component itself > REPL

App.svelte
<script>
    import Component from './Component.svelte';
    
    let reference
        
</script>

<Component bind:this={reference} {reference}/>
Component.svelte
<script>
    
    export let reference;
    
    $: reference && console.log('reference in component', reference)

</script>
Related