I am just starting with Svelte. I have a searchbar component and an unique instance of that component: main_searchbar. I want to focus that component from a different component.
So I export input in searchbar.svelte:
<script>
export let value = '';
export let input;
</script>
<span class="searchbar">
<input
class="search"
type="text"
name="search"
bind:value
bind:this={input}
>
</span>
Then I import it in main_searchbar.svelte:
<script context="module">
import Searchbar from './searchbar.svelte';
export let obj;
</script>
<Searchbar bind:this={obj}/>
Then I create a button to focus:
<script>
import {obj} from './main_searchbar.svelte';
function focus() {
obj.input.focus();
}
</script>
<button on:click={focus}>Focus</button>
And last the App.svelte:
<script>
import Main_searchbar from './main_searchbar.svelte'
import Focus from './focus.svelte'
</script>
<Main_searchbar/>
<Focus/>
Of course this doesnt work: https://svelte.dev/repl/c4eb67950c6240e593173431edb18e1a?version=3.38.2 What is the correct way of doing this in Svelte?
obj
points to? If you have more than one instance of searchbar.svelte, which one gets the focus? I think you should either opt for a store or dispatch an event. – Connor Low