App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
import React, { useState } from 'react'; import { Container, Form, Button, Row, Col, Card } from 'react-bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; const App = () => { const [searchQuery, setSearchQuery] = useState(''); const [videoData, setVideoData] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); // API Key from Google Developer Console const API_KEY = '####yourapikey####'; // Function to handle search const handleSearch = async () => { if (!searchQuery) return; setLoading(true); setError(''); setVideoData([]); try { const response = await fetch( `https://www.googleapis.com/youtube/v3/search?part=snippet&q=${searchQuery}&key=${API_KEY}&type=video` ); const data = await response.json(); setVideoData(data.items); } catch (error) { setError('An error occurred while fetching data'); } finally { setLoading(false); } }; return ( <Container className="my-4"> <h1 className="text-center">YouTube Video Search</h1> <Row className="my-3"> <Col> <Form.Control type="text" placeholder="Search for videos" value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} /> </Col> <Col> <Button variant="primary" onClick={handleSearch} disabled={loading}> {loading ? 'Searching...' : 'Search'} </Button> </Col> </Row> {error && <div className="alert alert-danger">{error}</div>} {/* Display Search Results */} <Row> {videoData.map((video) => ( <Col key={video.id.videoId} md={4} className="mb-4"> <Card> <Card.Img variant="top" src={video.snippet.thumbnails.medium.url} alt={video.snippet.title} /> <Card.Body> <Card.Title>{video.snippet.title}</Card.Title> <Card.Text>{video.snippet.description}</Card.Text> <Button variant="primary" href={`https://www.youtube.com/watch?v=${video.id.videoId}`} target="_blank" > Watch Video </Button> </Card.Body> </Card> </Col> ))} </Row> </Container> ); }; export default App; |