i am tying to implement dropdown
here is the image
now i want to add active class to option 1 and on keypress event like up and down i want to move between options
here is what i have tried
useEffect(() => {
let btns = document.getElementsByClassName("list-item");
console.log(btns[3]);
for (var i = 0; i < btns.length; i++) {
btns[0].classList.add("active");
btns[i].addEventListener("keydown", function (e) {
if (e.key === 38 || e.key === 40) {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace("active", "");
this.className += "active";
}
});
}
});
here is how i am rendering dropdown list
const options = ["Option1", "Option2", "Option3", "Option4"];
{open && (
<ul className="list" id="lists">
{options.map((option, i) => (
<li
onClick={() => {
setSelected(option);
setOpen(false);
}}
className="list-item"
>
{option}
</li>
))}
</ul>
)}
please help me i am stuck here from 2 days.
i can add active class to first option but it is not switching on up and down key press
thanks in advance