I have a <TextField/>
component that I am using from Svelte UX
I assigned it an id but when I try something like document.getElementById('the-id').focus()
, I get TypeError: Cannot read properties of null (reading 'focus')
and it does not work. I also tried .click()
Anyone know how this package works? I’ve tried reading their docs…
Thanks in advance!
3
Using the id
should work, if you wait for the element to be mounted first.
E.g. if you immediately want to focus, wait via onMount
:
<script>
import { onMount } from 'svelte';
onMount(() => {
// DOM interaction here
});
</script>
I generally would not recommend things like this, though, since it is easier to accidentally selecting things outside the current component.
You can get a reference to the element by binding inputEl
, this also will only be available after mount.
<script>
import { onMount } from 'svelte';
let input;
onMount(() => {
input.focus();
});
</script>
<TextField bind:inputEl={input} />
Another option should be to set an action via the actions
property. Actions receive the element as an argument, so you can get a reference that way.
For auto focus behavior, you can also use the autofocus
property, which internally adds an action that focuses.
2