Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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} />
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!