To create an Unsplash API photo search app using React, you will need to follow these steps:
- Create a new React app using
create-react-app
. - Install the
axios
library to make HTTP requests to the Unsplash API. - Register for an Unsplash developer account and obtain an API access key.
- Create a component for the search form, where users can enter their search query.
- Create a component for the search results, where the photos retrieved from the API will be displayed.
- In the search form component, use the
axios
library to make a GET request to the Unsplash API, passing in the search query and API access key as parameters. - In the search results component, map over the array of photos retrieved from the API and render each one as an image.
- Add error handling to the search form component in case the API request fails.
Here’s an example of what the code might look like:
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 |
import React, { useState } from 'react'; import axios from 'axios'; function App() { const [query, setQuery] = useState(''); const [photos, setPhotos] = useState([]); const searchPhotos = async (e) => { e.preventDefault(); const accessKey = 'YOUR_ACCESS_KEY_HERE'; try { const response = await axios.get(`https://api.unsplash.com/search/photos?query=${query}&client_id=${accessKey}`); setPhotos(response.data.results); } catch (error) { console.error(error); } }; return ( <div> <form onSubmit={searchPhotos}> <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} /> <button type="submit">Search</button> </form> <div> {photos.map((photo) => ( <img key={photo.id} src={photo.urls.small} alt={photo.description} /> ))} </div> </div> ); } export default App; |