'Adding a keyboard arrow navigation to Carousel Reactjs


I have written a piece of code that contains a carousel which i can navigate using the left and right arrows on my keyboard but its not working. Am stuck need help

import React, { useCallback, useEffect, useMemo, useState } from "react";
import Carousel from "react-material-ui-carousel";
import { Typography } from "@mui/material";


function App() {
  // State to programmatically set active child
  const [active Child, setActiveChild] = useState(0);

  // Basically items = [1, 2, 3, 4]
  const items = useMemo(() => [1, 2, 3, 4], []);

  // The Keypress Event Handler
  const changeChild = useCallback(
    (e) => {
      if (e.key === "ArrowLeft") {
        // If supposed previous child is < 0 set it to last child
        setActiveChild((a) => (a - 1 < 0 ? items.length - 1 : a - 1));
      } else if (e.key === "ArrowRight") {
        // If supposed next child is > length -1 set it to first child
        setActiveChild((a) => (a + 1 > items.length - 1 ? 0 : a + 1));
      }
    },
    [items]
  );

  // Set and cleanup the event listener
  useEffect(() => {
    document.addEventListener("keydown", changeChild);

    return function cleanup() {
      document.removeEventListener("keydown", changeChild);
    };
  });

  return (
    <div className="App">
      <Carousel
        index={activeChild} // <-- This controls the activeChild
        autoPlay={false} // 
        navButtonsAlwaysVisible
      >
        {items.map((i) => {
          return (
            <Typography align="center" key={i}>
              Child {i}
            </Typography>
          );
        })}
      </Carousel>
    </div>
  );
}

export default App;

Can someone please tell me why its not working or even provide a better solution to achieve keyboard navigation on a carousel in reactjs



Solution 1:[1]

I found the problem. and was able to fix it.

orignal section

<Typography align="center" key={i}>
    Child {i}
</Typography

What I changed it to

<Typography align="center" key={i}>
   Child {activeChild}
</Typography

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kaay