paint-brush
Integrating React Bricks With an External APIby@dsalinasgar
166 reads

Integrating React Bricks With an External API

by Diego SalinasMarch 18th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this tutorial, we will walk through the process of fetching a cat image from The Cat API, and rendering it in a React Bricks application.
featured image - Integrating React Bricks With an External API
Diego Salinas HackerNoon profile picture


If you’ve been following my tutorials, you know I’ve been building my website about tuxedo cats, “The tuxedo chronicles” entirely using React Bricks.


So far, I’ve been happy with my website, but I wanted to kick it up a notch and use APIs to fetch cat images according to their breed and display them as bricks on React Bricks.

Suffice it to say that I made it, and I want to show you how I did it. In this tutorial, we will walk through the process of fetching a cat image from The Cat API and rendering it in a React Bricks application.

Prerequisites

  • A working instance of React Bricks
  • Basic HTML, JS, CSS, and React knowledge
  • Knowledge of how to create and edit bricks (check this tutorial)

Step 0: What is The Cat API, and how does it work?

The Cat API is a public API service that allows developers to access a vast collection of images and information relating to domestic cats.


The API offers a variety of endpoints that can be accessed via HTTP requests and returns data in a variety of formats. In this case, we’re getting our data in JSON.


Since I want my website to be an homage to cats in every shape and size –and it turns out tuxedo isn’t a breed, I decided to fetch different breeds based on the breed list they offer.

Step 1: Define a page type

First, we need to define a page type for our cat page. In your ‘pageTypes.ts file,’ add the following code:

This code defines a 'cat' page

{
    name: 'cat',
    pluralName: 'cats',
    getExternalData: (page) =>
      fetch(`https://api.thecatapi.com/v1/breeds/search?q=${page.slug}`)
        .then((response) => response.json())
        .then((data) => {
          if (data[0] && data[0].reference_image_id) {
            return {
              ...data[0],
              imageUrl: `https://cdn2.thecatapi.com/images/${data[0].reference_image_id}.jpg`,
            };
          } else {
            throw new Error('Cat not found');
          }
        })
        .catch((error) => {
          console.log(error);
          return {};
        }),
  },

A peek inside the brick

This TypeScript code is part of a page type definition in React Bricks. It defines a page type named 'cat'’ Here's a breakdown of the code:


  • name: This is the name of the page type. It's used internally by React Bricks to identify the page type.
  • pluralName: This is the plural form of the name. It's used in the React Bricks admin interface.
  • getExternalData: This is a function that fetches external data for the page. It's called with the page object as an argument, which includes the slug of the page.

How does it work?

  1. The function starts by making a fetch request to TheCatAPI, using the page's slug as a query parameter. It then converts the response to JSON.
  2. If the fetched data includes a reference_image_id, it returns the data along with an imageUrl constructed using the reference_image_id. If the data does not include a reference_image_id, it throws an error with the message 'Cat not found'.
  3. If an error occurs during the fetch or the data conversion, it logs the error and returns an empty object.

Step 2: Create a Cat brick

Next, we need to create a block to display the cat image. In your ‘/bricks’ directory, create a new file named ‘Cat.tsx’ and add the following code:

import React from 'react'
import { types } from 'react-bricks/frontend'

interface CatProps {
  id: string
  name: string
  description: string
  temperament: string
  imageUrl: string
}

const Cat: types.Brick<CatProps> = ({
  id,
  name,
  description,
  temperament,
  imageUrl,
}) => {
  if (!id || !name || !description || !temperament || !imageUrl) {
    return (
      <div className="text-center text-red-500 underline text-xl">
        Cat not found!
      </div>
    )
  }
  return (
    <div className="container mx-auto px-4">
      <img src={imageUrl} className="mx-auto w-1/2 mb-4" />
  
      <h1 className="text-5xl font-extrabold text-center mb-6 mt-4">{name}</h1>
      <h2 className="text-xl  text-center mb-4 mt-4"> {description}</h2> 
      <h2 className="text-xl italic text-center mb-4 mt-4"> {temperament} </h2> 
    </div>
  )
}

Cat.schema = {
  name: 'cat',
  label: 'Cat',
  mapExternalDataToProps: (externalData, brickProps) => ({
    id: externalData.id,
    name: externalData.name,
    description: externalData.description,
    temperament: externalData.temperament,
    imageUrl: externalData.imageUrl,    
  }),

  // Sidebar Edit controls for props
  sideEditProps: [],

}

export default Cat

A peek inside the brick

This TypeScript file defines a React component named Cat. Here's a breakdown of the code:


  • Import statements: The necessary modules are imported. This includes React from the react package and types from the react-bricks/frontend package.

  • Interface definition: The CatProps interface is defined. This interface specifies the shape of the props that the Cat component expects to receive: id, name, description, temperament, and imageUrl. All of these props are of type string.

  • Component definition: The Cat component is defined as a functional component. It destructures its props according to the CatProps interface. Inside the component, it first checks if all the props are truthy. If any of them are falsy, it renders a "Cat not found!" message. If all props are truthy, it renders a div containing an image and some text elements displaying the cat's information.

  • React Bricks schema: The Cat.schema object is defined. This object is used by React Bricks to understand how to handle the Cat component.


Now, if you go back to the breeds list on the Cat API, you’ll see that each breed has a series of properties we can call. I selected a few just to see if it worked, but feel free to try with different properties.


This means that when the Cat brick is rendered, it will receive the id, name, description, temperament, and imageUrl from the external data as props. All of these props are of type string. These props can then be used inside the Cat brick to display the cat's information.


But before you see your brick in action, there’s one little step we must take so things work right.


Read more: What is a brick?

Step 3: Import the cat component

import HeroUnit from './custom/MyHeroUnit'
import reactBricksUITheme from './react-bricks-ui'
import Thumbnail from './Thumbnail'
import File from './File'
import Gallery from './Gallery'
import Pokemon from './custom/Pokemon'
import Cat from './custom/Cat'


RB tip: If you’ve been following the other tutorials, you should have a ‘File,’ ‘Gallery,’ and ‘Thumbnail’ bricks. If you don’t, just erase those imports.


Anyway, just add the ‘Cat’ import at the bottom like I did, and you should be good.


The Cat component can now be used in the ‘index.ts’ file. This is a common practice in React and TypeScript to organize code into modular, reusable components.


But that’s not it. We need to add our Cat brick to the themes in React Bricks so you can use it on your website.


If you look at the ‘index.ts’ file, you’ll see there’s a const bricks: types.Theme line. This line of code defines a constant named bricks, which is an array of types.Theme. Theme is a type imported from the ‘react-bricks/frontend’ package.


RB tip: In the context of React Bricks, a Theme is an object that defines a set of categories, and each category contains a set of bricks (components). This bricks array is used to configure the available bricks in the React Bricks visual editor.


Let’s add our ‘Cat’ category below the ‘Pokemon’ one.


{
        categoryName: 'Cats',
        bricks: [Cat], // External data Bricks
      },

A peek inside the brick

  • The 'Cats' category includes one external data brick: Cat. This brick uses the getExternalData function in its page type to fetch data from an external source and the mapExternalDataToProps function in its schema to map this data to its props. This configuration allows you to use these bricks in the React Bricks visual editor to build your pages.

Step 4: Put it all together in React Bricks

Let’s head to our React Bricks instance. You’ll notice there’s a new page called “Cats.” The page is empty, but don’t worry; we’ll take care of that in a second.

Do you remember the breed list from The Cat API? Let’s go back to the list and pick one. For this tutorial, I’ll pick the Bambino because it’s Italian, and they look like cute bald tuxedo cats.


Click on the ‘Create new cat’ icon, write the name of your cat,  based on the list of breeds, then on “Add your first block” and look for the block called “Cat.”


Click on it. If everything goes right, you should see a picture and the set of traits we chose. Keep in mind that I’m using cats with just one name in this tutorial.


So cute!


But I digress. Let’s go back to the code. If you ‘Cat.tsx’, you’ll notice I’m only declaring a handful of properties and many more are on the breeds list. I chose them because they were the most important qualities to show here, but you can experiment and add as many as you want.


And that’s it. You’ve officially called an API to fetch cat data and display it on React Bricks as a Brick. In our next tutorial, I’ll show you how to create a Cats page with each cat breed as a subpage. Stay tuned.

Step 5: Commit and push changes

You can now commit the changes and push them to your Git remote by using the editor interface or the Git CLI.


Once your code is pushed to the remote, if you connected Vercel or Netlify to your repo, it will start the rebuild of your website and you should be done.


If you want to be extra sure, go to ‘Settings’ and click on ‘deploy production’ to deploy your website.


Don’t forget to read our docs if you feel stuck, or try our gamified tutorial for a juicy prize.

Also, keep in mind you can ask the community and join our Discord or Slack channels to get insights from other developers and React enthusiasts.