DEV Community

Daniel Deutsch
Daniel Deutsch

Posted on

2 easy ways to get data from Unsplash.com in React

unsplash.com/photos/k_T9Zj3SE8k

Since Unsplash.com released their API and I just love their content, I decided to write a short article on how to use it with React. Unsplash is awesome! :) Enjoy.

➡️ Github Repo is available here ⬅️


"Everything negative - pressure, challenges - is all an opportunity for me to rise." - Kobe Bryant

Set up the basics

To set up the basics, I use the code base from another project I did, using:

  • create-react-app
  • React components that basically render images in a list

Fetch data with the fetch API

componentDidMount() {
    fetch('https://api.unsplash.com/photos/?client_id=' + cred.APP_ID)
        .then(res => res.json())
        .then(data => {
            this.setState({ imgs: data });
        })
        .catch(err => {
            console.log('Error happened during fetching!', err);
        });
}
Enter fullscreen mode Exit fullscreen mode
  • use componentDidMount lifecycle when fetching data (DOM is represented)
  • describe a fetch method using Promise functionality
  • transform the call into a JSON object and pass it into state
  • after that, simply render out each image from the fetched link

➡️ See the Github Repo after those steps ⬅️

Fetch data using a library

Fetching can also be accomplished by one of many libraries. I will use axios, since it provides cool features like:

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

So the next steps are:

  • add the axios package
  • simply adapt the fetch method to the methods from the axios package
componentDidMount() {
    axios
        .get('https://api.unsplash.com/photos/?client_id=' + cred.APP_ID)
        .then(data => {
            this.setState({ imgs: data.data });
        })
        .catch(err => {
            console.log('Error happened during fetching!', err);
        });
}
Enter fullscreen mode Exit fullscreen mode

Very easy and works well:)

➡️ See the Github Repo after those steps ⬅️

Looks like this:

Add search feature

  • adapt your fetched link (add query and search parameters)
  • make your request dynamic, connecting the search query to your app
  • add a searchbar component
  • make sure to bind all methods (use the arrow functions or bind them manually)
performSearch = query => {
  axios
    .get(
      `https://api.unsplash.com/search/photos/?page=1&per_page=10&query=${query}&client_id=${cred.APP_ID}`
    )
    .then(data => {
      this.setState({ imgs: data.data.results });
    })
    .catch(err => {
      console.log('Error happened during fetching!', err);
    });
};
Enter fullscreen mode Exit fullscreen mode

Polish up React code

  • use the ref-attribute for the input
this.props.onSearch(this.query.value);
---
ref={input => (this.query = input)}
Enter fullscreen mode Exit fullscreen mode
  • set a default for your performSearch method and put the performSearch into the componentDidMount lifecycle
  • render out a different component when no images can be found with an if statement
  • use conditional rendering to render a paragraph when the fetch is not finished (setting a flag to the state and changing it in the fetch method)
<div className="main-content">
    {this.state.loadingState
        ? <p>Loading</p>
        : <ImgList data={this.state.imgs} />}
</div>
Enter fullscreen mode Exit fullscreen mode

➡️ See the Github Repo after those steps ⬅️


⭐ That was incredible easy and already shows how much you can do with the API :)


Adapt to Unsplash guidelines

When using an API always, ALWAYS, make sure to read their guidelines.
➡️ Unsplash API guidelines

So as an example here, I didn't credit Unsplash or the photographer. Therefore I have to improve my app by retrieving more information from the data and adding credits to the owners:

const Img = props =>
    <li>
        <a href={props.link}>
            <img src={props.url} alt="Unsplash Image here" />
        </a>
        <p>
            Photo by
            <a href={props.user}>{props.name}</a>
            <a href={props.link}> See on Unsplash</a>
        </p>
    </li>;
Enter fullscreen mode Exit fullscreen mode

Now it looks like

➡️ See the finished app on Github ⬅️

Useful links & credits

  • Unsplash.com
  • I did a treehouse course, that covers an app with a similar approach:

If you gained something from this article let me know with a comment or heart. Make sure to follow for more :)

Top comments (1)

Collapse
 
csamboni profile image
CristianSAM

Can you do the same concept with a collection from unsplash?