screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState, useEffect } = React function App() { const [imageUrl, setImageUrl] = useState(null); const [page, setPage] = useState(1); const perPage = 10; const [totalHits, setTotalHits] = useState(null); const [currentImageIndex, setCurrentImageIndex] = useState(0) useEffect(() => { fetchImages(); }, []); const fetchImages = () => { fetch(`https://pixabay.com/api/?key=34464713-d6983b6f7516f75f27cdcbb6b&q=god&page=${page}&per_page=${perPage}`) .then(response => response.json()) .then(data => { console.log(data); setImageUrl(data.hits[currentImageIndex].webformatURL); setTotalHits(data.totalHits); }) .catch(error => { console.error(error); }); }; const prevImage = () => { if (currentImageIndex > 0) { setCurrentImageIndex(currentImageIndex - 1); } else { setPage(page - 1); setCurrentImageIndex(perPage - 1); if (page < 1) { setPage(1); setCurrentImageIndex(0); } } fetchImages(); }; const nextImage = () => { if (currentImageIndex < perPage - 1 && currentImageIndex < totalHits - 1) { setCurrentImageIndex(currentImageIndex + 1); } else { setPage(page + 1); setCurrentImageIndex(0); if (page * perPage > totalHits) { setPage(Math.ceil(totalHits / perPage)); } } fetchImages(); }; return ( <div className="container"> <h3>React Js Get Image From API | Fetch API</h3> <img src={imageUrl} alt="Image" /> <div> <button onClick={prevImage}>Previous</button> <button onClick={nextImage}>Next</button> </div> </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> * { box-sizing: border-box; } .container { margin: 0 auto; width: 600px; text-align: center; box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.12), 0 2px 4px 0 rgba(0, 0, 0, 0.24); padding: 20px; } .container h3 { font-size: 24px; color: #333; margin-bottom: 20px; } .container img { max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } </style> </body> </html>