Build a dropdown component with keyboard navigation.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
<template>
<div>
<button @click="isOpen = !isOpen">Toggle</button>
<ul v-if="isOpen" @keydown="onKeydown">
<li
v-for="(option, i) in options"
:key="option"
:class="{ focused: i === focusedIndex }"
>
{{ option }}
</li>
</ul>
</div>
</template>
<script setup>
import { ref } from 'vue';
const options = ['A', 'B', 'C'];
const isOpen = ref(false);
const focusedIndex = ref(-1);
const onKeydown = (e) => {
if (e.key === 'ArrowDown') {
focusedIndex.value = (focusedIndex.value + 1) % options.length;
} else if (e.key === 'ArrowUp') {
focusedIndex.value = (focusedIndex.value - 1 + options.length) % options.length;
}
};
</script>