Random dog images

  • React
  • Exercises
  • Random dog images

React exercise number 9

  • Async Requests
  • Components
  • JSX
  • useEffect
  • useState

Random dog images

Let's build a React app that shows the user a random dog image when a button is clicked!

Quick start

Start with this code as a boilerplate for the exercise.


To do this, we are going to use the Dog API, which provides a collection of open-source dog pictures over HTTP endpoints.

The endpoint you should use is this one:

GET https://dog.ceo/api/breeds/image/random

That returns a JSON structured as follows:

    "message": "https://images.dog.ceo/breeds/spaniel-irish/n02102973_220.jpg",
    "status": "success"


Step 1

Have a button that when clicked properly calls the API endpoint and shows the user the returned dog image.

Step 2

Implement a loading state, for when the app is waiting for a response from the API.

  • The loading state can be the string Loading... of a GIF image showing a loading spinner.

Step 3

Use components to organize your app. You should have two components, a <GenerateImageButton /> component for the button, and a <DogImage /> component to show the image of the dog.

Step 4

If we are waiting for an API response, we shouldn't be able to click the button again. Implement a disabled state on the button when we are waiting for an API response.

Step 5

What should happen if the request fails? Implement a proper error message to handle this case.

  • The error message should be the string Whoops, something went wrong! within a red box.
  • You should write this in a separate component named <ErrorMessage />.

Step 6

When the app starts, there is no dog image, because no one has clicked the button yet. Write some code in order to show a random dog image when the app starts without the need for a button click.