<div id="app"></div>
.app-body {
display: flex;
justify-content: center;
}
.slider-container {
display: flex;
align-items: center;
margin-top: 50px;
}
.slider-container img {
width: 600px;
height: 400px;
max-width: 100%;
}
.previous-button {
font-size: 30px;
background-color: rgb(213, 225, 237, 0.25);
height: 45px;
transform: translate(60px, 0);
}
.next-button {
font-size: 30px;
background-color: rgb(213, 225, 237, 0.25);
height: 45px;
transform: translate(-60px, 0);
}
/*
* https://frontendeval.com/questions/image-carousel
*
* Build an auto-playing image carousel
*/
import { useState, useEffect } from "https://cdn.skypack.dev/react@17.0.1";
const getImages = async ({period}) => {
const URL = `https://www.reddit.com/r/aww/top/.json?t={period}`;
try {
const response = await fetch(URL);
if (response.ok) {
const data = await response.json();
const images = data.data?.children
.map((i) => i.data.url_overridden_by_dest)
.filter((url) => url.slice(-3) === "jpg"); //where extension .jpg
return images;
}
} catch (e) {
console.log("error on fetch", e);
}
};
const Slider = ({period}) => {
const [srcArray, setSrcArray] = React.useState([]);
const [visible, setVisible] = React.useState(0);
React.useEffect(() => {
getImages({period}).then((data) => {
setSrcArray(data);
});
}, []);
React.useEffect(() => {
const timeoutID = setTimeout(() => {
goNext();
}, 3000);
return () => clearTimeout(timeoutID);
}, [visible]);
const goNext = (s) =>
setVisible((s) => (s === srcArray.length - 1 ? 0 : s + 1));
const goBack = (s) =>
setVisible((s) => (s === srcArray.length - 1 ? 0 : s - 1));
return (
<>
{srcArray.length > 0 && (
<div className="slider-container">
<button className="previous-button" onClick={goBack}>
<
</button>
<img src={srcArray[visible]} />
<button className="next-button" onClick={goNext}>
>
</button>
</div>
)}
</>
);
};
const App = () => {
return (
<div className="app-body">
<Slider period={'day'} />
</div>
);
};
ReactDOM.render(<App />, document.getElementById("app"));
View Compiled
This Pen doesn't use any external CSS resources.