useArrayNav.js 541 B

1234567891011121314151617181920212223
  1. import {useState} from 'react';
  2. const useArrayNav = (array) => {
  3. const [index, setIndex] = useState(0);
  4. const navigate = e => {
  5. const {direction} = e.currentTarget.dataset;
  6. if (direction === 'next') {
  7. index + 1 === array.length ? setIndex(0) : setIndex(index + 1);
  8. } else if (direction === 'prev') {
  9. index - 1 < 0 ? setIndex(array.length - 1) : setIndex(index - 1);
  10. }
  11. }
  12. return {
  13. index,
  14. setIndex,
  15. navigate
  16. };
  17. }
  18. export default useArrayNav