refactor(switch): focus ref in afterUpdate method

This commit is contained in:
Eric Liu 2019-12-25 07:17:51 -08:00
commit 52dd244516

View file

@ -6,8 +6,8 @@
export let disabled = false; export let disabled = false;
export let style = undefined; export let style = undefined;
import { afterUpdate, getContext } from 'svelte';
import { cx } from '../../lib'; import { cx } from '../../lib';
import { getContext } from 'svelte';
const id = Math.random(); const id = Math.random();
const { currentId, add, update, change } = getContext('ContentSwitcher'); const { currentId, add, update, change } = getContext('ContentSwitcher');
@ -16,10 +16,13 @@
add({ id, text, selected }); add({ id, text, selected });
$: selected = $currentId === id; afterUpdate(() => {
$: if (selected && buttonRef) { if (selected) {
buttonRef.focus(); buttonRef.focus();
} }
});
$: selected = $currentId === id;
</script> </script>
<button <button
@ -36,10 +39,10 @@
on:mouseenter on:mouseenter
on:mouseleave on:mouseleave
on:keydown on:keydown
on:keydown={event => { on:keydown={({ key }) => {
if (event.key === 'ArrowRight') { if (key === 'ArrowRight') {
change(1); change(1);
} else if (event.key === 'ArrowLeft') { } else if (key === 'ArrowLeft') {
change(-1); change(-1);
} }
}} }}