Unsplash API with React Part 1

Photo by Desola Lanre-Ologun on Unsplash

Unsplash is a great resource for high resolution photographs that can be used for free for commercial and noncommercial purposes. It gives exposure for professional photographers and hobbyists alike. From their license page, “You do not need to ask permission from or provide credit to the photographer or Unsplash, although it is appreciated when possible…” I personally post nature photographs from hikes on Unsplash and it is a joy to see how much activity they get. One of my favorite shots that I took is a starry night shot in Red Rock State Park in Sedona, Arizona and has over 5.5 million views and over 47k downloads.

Photo by Darryl Brian on Unsplash

For any reason, if you’re looking for a beautiful image for a wallpaper, a blog post, or a website there are some pretty talented photographers - more specifically 200,000 photographers - nice enough to contribute to Unsplash and allow their combined two million images to be used with or without credit.

Unsplash also allows their library to be accessible via their very simple to use API. Here I’d like to share a very basic way to connect to their API to help you jump start your project. I’ll be using React for this example and although I’ll be sharing the relevant snippets of code to put this app together, a basic level of understanding of React will be helpful as my focus will be on the Unsplash API. Here is a live demo of what we’ll be building towards so you have an idea of what we’re striving for. It is a essentially a replicate of Unsplash. It is not intended to move out of demo mode and into production to abide by Unsplash’s API Guidelines. It is simply an education exercise for you and I. This tutorial will be broken up into several parts but by the end you should be able to fetch data, display an initial set of images on page load, open a more full version of a selected image, load more images via a button click, and search for images via an input field. Shall we get started?

First, create an Unsplash account and then create a New Application on their developers’ page. You’ll then be given an Access and Secret Key.

Next, create your React app using npx create-react-app my-app. To fetch our data we will use axios. Install this by running npm i axios in your command line.

After clearing out the placeholder code in your App.js file, convert the App function into a class based component, set up the state, and add constants like so:

import React, { Component } from 'react'import './App.css'class App extends Component {
constructor(props) {
super(props)
this.state = {
gallery: [],
searchedQuery: '',
}
}
ROOT = `https://api.unsplash.com/`
KEY = `?client_id=<your-access-key-here>`
PERPAGE = `&per_page=30`
render() {
return (
<div className="App">
<h1 className="text-center">{this.state.searchedQuery}</h1>
</div>
);
}
}
export default App

The gallery property is where will store the fetched data and searchedQuery will be used for the title of our image gallery. These constants will be used to build our api url for when we fetch our data. Place your unique access key from your unsplash application where indicated in the KEY value. The PERPAGE option indicates how many images are fetched per get request. Ten is the default and 30 is the max which is why we have set our value to30.

Now we will actually fetch our initial data. First, import axios at the top of your App.js — import axios from ‘axios’ and then write out a function to fetch the data:

fetchInitialImages = () => {
this.setState({ searchedQuery: 'Curated Collection'})
axios.get(`${this.ROOT}photos${this.KEY}${this.PERPAGE}&page=1`)
.then(res => {
let results = res.data
this.setState(() => {
return { gallery: [...results] }
}, () => { console.log('this.state.gallery = ', this.state.gallery)})
})
.catch(error => console.log(error))
}

I’m starting off by setting the state with a default title called 'Curated Collection' since the data we a fetching is from the latest of Unsplash’s curated selection which are hand-selected by their own editorial staff. Axios returns a promise that will resolve either a response or an error object. If a response object is returned we can store the data property in a results variable. This will be an array of 30 objects that has a ton of properties that we can play with including links to images at different sizes, descriptions, the photographer’s user info, and stats such as number of likes.

Now is a good time to mention that while in demo mode, your rate limit to the Unsplash API is 50 requests per hour. Once you exceed 50, an error object is returned instead. Once you feel your app is ready to launch you can apply for production mode and if approved Unsplash will increase your rate limit status to 5000 requests per hour. As you’re developing you can check your remaining requests by looking at the Requests & Usage section of your applications page on the Unsplash Developers site where you created your app.

Okay, now to fire our function on load we can use the componentDidMount() lifecycle hook:

componentDidMount() {
this.fetchInitialImages()
}

You may have noticed the console log in the callback function of the setState. Feel free to check your console to ensure your data was retrieved successfully. While you’re there, take a look through the data and notice the amount of properties each object has. Now you’ll begin to realize the potential of this api.

From here, you can create a Gallery component that maps through our data and builds out a gallery of images by outputting a snippet of html for each item in the array. We can create it as a functional component and accept the data via props. We will pass in the data in the App component soon:

import React from 'react'import './styles.css'const Gallery = (props) => {
const { gallery } = props
return (
<div className="content">
<section className="grid">
{gallery.map( (image, index) => (
<div
key={image.id}
>
<img
src={image.urls.small}
alt={image.description}
/>
</div>
))}
</section>
</div>
)
}
export default Gallery

For your Gallery component’sstyles.css feel free to use the following styles:

.content {
max-width: 1200px;
margin: 20px auto;
display: flex;
flex-direction: column;
align-items: center;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
padding: 25px;
grid-gap: 25px;
grid-auto-flow: dense;
align-items: stretch;
width: 100%;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 2px;
}

These styles will display your gallery using CSS Flexbox and Grid Layout Module so you don’t have to worry about building rows and columns yourself.

Now you can import your Gallery component into your App component which may look something like this depending on how you structured your files. Don’t forget to pass in your data as props.

import React, { Component } from 'react'
import axios from 'axios'
import Gallery from './Components/Gallery'
.
.
.
render() {
return (
<div className="App">
<Gallery gallery={this.state.gallery}/>
</div>
);
}
.
.
.

At this point you should be able to see your gallery of pictures.

Congratulations! You’ve successfully connected your app to the Unsplash API and displayed images from the data 😊

For the rest of this tutorial series where we will learn how to view a full version of a selected image, add a search form so users can search for images of different categories, and we’ll add a ‘Load More’ button. See you there!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store