<div id="app"></div>
.main{
display: flex;
align-items: center;
justify-content: center;
width: 100wh;
height: 100vh;
}
.img-container{
display: flex;
align-items: center;
justify-content:space-between;
border: 1px solid black;
width: 24rem;
height: 24rem;
background-size: 24rem;
border-radius: 4px;
}
.img-button{
font-size:20px;
z-index:10;
background: grey;
color:white;
height: 70px;
width: 70px;
border-radius:100%;
border: 0px;
opacity:0.5;
text-align: center;
}
.img-button:hover{
opacity:0.8;
cursor:pointer;
}
/*
* https://frontendeval.com/questions/image-carousel
*
* Build an auto-playing image carousel
*/
const App = () => {
const [currImageIndex, setCurrImageIndex] = React.useState(0);
const [images, setImages] = React.useState();
React.useEffect(() => {
const fetchData = async () => {
const children = await fetch("https://www.reddit.com/r/aww/top/.json?t=all").then(res => res.json()).then(res => res.data.children);
const arrayOfImages = children.map(el => el.data.url_overridden_by_dest).filter(el => el.includes(".jpg"))
setImages(arrayOfImages)
}
fetchData()
},[])
React.useEffect(() => {
const interval = setInterval(() => {
if(images){
setCurrImageIndex(prev => (prev + 1) % images.length);
}
}, 3000);
return () => clearInterval(interval)
}, [currImageIndex])
const increaseIdx = () => {
const imgLength = images.length
const newIdx = (currImageIndex + 1) % imgLength
setCurrImageIndex(newIdx)
}
const decreaseIdx = () => {
const imgLength = images.length
const newIdx = (imgLength + currImageIndex - 1) % imgLength
setCurrImageIndex(newIdx)
}
//
if (!images){
return <div>Loading...</div>
}
const thisImage = images[currImageIndex]
return <div class="main">
<div class ="img-container" style = {{backgroundImage:`url(${thisImage})`}}>
<button onClick={decreaseIdx} class="img-button"> {"<"} </button>
<button onClick={increaseIdx} class= "img-button"> {">"}</button>
</div>
</div>
}
ReactDOM.render(<App />, document.getElementById('app'));
View Compiled
This Pen doesn't use any external CSS resources.