Created
March 20, 2023 11:08
-
-
Save nrubel/2a53adf63c1563d79f31115c541cd7a1 to your computer and use it in GitHub Desktop.
Very basic react carousel
This file contains hidden or 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 { useState, useEffect, useRef } from 'react'; | |
export default function CatFriends() { | |
const [index, setIndex] = useState(0); | |
const ref = useRef(null); | |
useEffect(() => { | |
clearInterval(ref.current); | |
ref.current = setInterval(() => { | |
setIndex(index < catList.length - 1 ?index + 1 : 0) | |
}, 3000); | |
return () => { | |
clearInterval(ref.current); | |
} | |
}, [index]); | |
console.log(index) | |
return ( | |
<> | |
<nav> | |
<button onClick={() => { | |
if (index === 0) { | |
setIndex(catList.length - 1) | |
} else { | |
setIndex(index - 1); | |
} | |
}}> | |
Prev | |
</button> | |
<button onClick={() => { | |
if (index < catList.length - 1) { | |
setIndex(index + 1); | |
} else { | |
setIndex(0); | |
} | |
}}> | |
Next | |
</button> | |
</nav> | |
<div> | |
<ul> | |
{catList.map((cat, i) => ( | |
<SlideItem key={cat.id} {...{i, index, src: cat.imageUrl}} /> | |
))} | |
</ul> | |
</div> | |
</> | |
); | |
} | |
const catList = []; | |
for (let i = 0; i < 10; i++) { | |
catList.push({ | |
id: i, | |
imageUrl: 'https://placekitten.com/250/200?image=' + i | |
}); | |
} | |
const SlideItem = ({i, index, src}) => { | |
const ref= useRef(null) | |
useEffect(() => { | |
if(i === index) { | |
ref.current.scrollIntoView({ | |
behavior: 'smooth', | |
block: 'nearest', | |
inline: 'center' | |
}) | |
} | |
}, [i, index]) | |
return ( | |
<li ref={ref}> | |
<img | |
className={ | |
index === i ? | |
'active' : | |
'' | |
} | |
src={src} | |
alt={'Cat #' + i + 1} | |
/> | |
</li> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment