Created
June 1, 2020 23:07
-
-
Save redochka/f98d993d331a72f82d1e49f6942588de to your computer and use it in GitHub Desktop.
Keyboard navigation in react bootstrap carousel before first click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react'; | |
import Carousel from 'react-bootstrap/Carousel'; | |
interface StCarouselParams { | |
activeIndex: number | |
photos: string[] | |
} | |
const StCarousel = (props: StCarouselParams) => { | |
const [activeIndex, setActiveIndex] = useState(props.activeIndex); | |
const goBack = () => { | |
setActiveIndex((activeIndex - 1) < 0 ? 0 : (activeIndex - 1)); | |
if ((activeIndex - 1) < 0) { | |
setActiveIndex(props.photos.length - 1); // Allow carousel to loop | |
} else { | |
setActiveIndex(activeIndex - 1); | |
} | |
}; | |
const goNext = () => { | |
if ((activeIndex + 1) < props.photos.length) { | |
setActiveIndex(activeIndex + 1); | |
} else { | |
setActiveIndex(0); // Allow carousel to loop | |
} | |
}; | |
useKeyPress(); | |
// https://usehooks.com/useKeyPress/ | |
function useKeyPress() { | |
const upHandler = (event: KeyboardEvent) => { | |
const KEY_CODE_LEFT = 37; | |
const KEY_CODE_RIGHT = 39; | |
const { keyCode } = event; | |
if (keyCode === KEY_CODE_LEFT) { | |
goBack(); | |
} | |
if (keyCode === KEY_CODE_RIGHT) { | |
goNext(); | |
} | |
}; | |
// Add event listeners | |
useEffect(() => { | |
window.addEventListener('keyup', upHandler); | |
// Remove event listeners on cleanup | |
return () => { | |
window.removeEventListener('keyup', upHandler); | |
}; | |
}, [activeIndex]); // Ensures that effect is run on componentDidUpdate in addition to mount and unmount | |
} | |
const onSelect = (selectedIndex: number) => { | |
setActiveIndex(selectedIndex); | |
}; | |
return ( | |
<Carousel interval={null} controls={true} keyboard={false} activeIndex={activeIndex} onSelect={onSelect}> | |
{props.photos.map((photo: any, index: any) => ( | |
<Carousel.Item key={index}> | |
<div className="diaporama__image" | |
style={{ backgroundImage: `url('${photo}')` }}/> | |
</Carousel.Item> | |
))} | |
</Carousel> | |
); | |
}; | |
export default StCarousel; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In relation to: