Edit: sadly the wrapping approach used in this answer doesn't seem to work for focusing inputs: https://svelte.dev/repl/41625a0612354910aaa59c5a71499977?version=3.50.1
I am using the useFocus() directive from Svelte Navigator. I have an Input component I use for input boxes - I'd like to add a prop isFocused so one instance of Input can be focused but other instances of Input will not be focused.
How can I use use:registerFocus conditionally in Svelte?
Input.svelte:
<script>
import { useFocus } from "svelte-navigator";
const registerFocus = useFocus();
// How do I makes the component only enable use:registerFocus if isFocused is true?
export let isFocused
export let value
const maybeRegisterFocus = (element, isFocused) => {
console.log(`Registering focus for '${value}': ${isFocused}`)
if (isFocused) {
registerFocus(element);
}
return {
update: (isFocused) => {
console.log(`Updating for element`, element)
if (isFocused) {
registerFocus(element);
}
return null;
},
destroy: () => {
return null;
},
};
};
</script>
<input use:maybeRegisterFocus={isFocused} value={value} />
App.svelte:
<script>
import { Router, Route } from "svelte-navigator";
import Input from "./Input.svelte"
</script>
<Router>
<Route>
<h1>
The first input box shoudl be focused.
<Input isFocused={true} value="First text box should be focused"/>
<Input isFocused={false} value="Second text box should not be focused"/>
</h1>
</Route>
</Router>