I am fetching company logos using react redux in a one component from [clearbit][1], and slicing to display 4 logos like this Results.slice(0, 4).map((item) => ( <Logo />
in a different component.
Now I want to create focus on the first logo to the right and navigate using left/right keys. This is what I have done. I am not getting any errors but am also not getting what I want
import styles from "./styles.module.scss";
import React, { useEffect, useReducer } from "react";
import { useSelector } from "react-redux";
import Logo from "./components/Logo/Logo";
import useKeyPress from "./usePressKey";
const initialState = { selectedIndex: 0 };
const bingResults = []
function NavigationReducer(state, action) {
switch (action.type) {
case "arrowLeft":
return {
selectedIndex:
state.selectedIndex !== 0 ? state.selectedIndex - 1 : bingResults.length - 1
};
case "arrowRight":
return {
selectedIndex:
state.selectedIndex !== bingResults.length - 1 ? state.selectedIndex + 1 : 0
};
case "select":
return { selectedIndex: action.payload };
default:
throw new Error();
}
}
const DislayLogos = () => {
const { bingResults } = useSelector((state) => state.search);
const [state, dispatch] = useReducer(NavigationReducer, initialState);
const arrowLeftPressed = useKeyPress("ArrowLeft");
const arrowRightPressed = useKeyPress("ArrowRight");
useEffect(() => {
if (arrowLeftPressed) {
dispatch({ type: "arrowLeft" });
}
}, [arrowLeftPressed]);
useEffect(() => {
if (arrowRightPressed) {
dispatch({ type: "arrowRight" });
}
}, [arrowRightPressed]);
return (
<main>
<div className={styles.mainHeader}>
<header className={styles.logoHeader}>
{bingResults.slice(0, 4).map((item) => (
<Logo
key={item.id}
name={item.name || item.title}
imgSrc={item.logo}
onClick={() => {
dispatch({ type: "select", payload: 1 });
}}
style={{
cursor: "pointer",
color: 1 === state.selectedIndex ? "grey" : "black"
}}
role="button"
aria-pressed={1 === state.selectedIndex}
tabIndex={0}
onKeyPress={(e) => {
if (e.key === "Enter") {
dispatch({ type: "select", payload: 1 });
e.target.blur();
}
}}
/>
))}
</header>
</div>
</main>
);
};
export default DisplayLogos;
Does anyone has a way around this?
[1]: https://clearbit.com/docs#autocomplete-api