Let's build with Astro and React

Let's build with Astro and React

Introduction

Astro is a Multi-Page all-in-one framework to help you build modern websites fast and easily with less or no Javascript offering very high performant and neat experience websites. With Astro, you can build a website with any UI framework of your choice like Preact, Svelte, React, Vue, Solid, Lit, and other UI frameworks.

Click here to try Astro in your browser

What you will learn

In this tutorial, we are going to cover the basics of Astro, routing in Astro, dynamic routing in Astro, fetching APIs in Astro, and Using Astro with Reactjs

Getting Started With Astro

To build our project, first, we need to create an Astro startup project

npm create astro@latest

After installation, your project structure should look like this

To run our Astro project, we use the command below

npm run dev

Astro ships with built-in support for typescript. We can directly write TypeScript in our Astro component. Astro components end with the extension .astro

Now that we have installed Astro, let's install React. To install React, run;

# Using NPM

npx astro add react

# Using Yarn yarn astro add react

# Using PNPM pnpm astro add react

We need to install the dependencies manually.

npm install @astrojs/react

Most times, the command above installs everything you need but in case you cannot find react, run this

npm install react react-dom

Now, head over to your astro.config.mjs file and paste this

import { defineConfig } from 'astro/config';

import react from '@astrojs/react';

export default defineConfig({

// ...

integrations: [react()],

})

Styling

For our styling, we are going to be using tailwind css.To Set up Tailwind CSS, run the command below

To install automatically,

npx astro add tailwind

The command above should set up the configurations and get you started. If you are facing any issue involving tailwind configuration, click this link

Let's begin the project

Today, we are going to be building a basic movie database, to display a list of movies and also get information about the movies.

First, in your src/ directory, we are going to be creating a few folders. The names of the folders are

  1. Component folder. This folder will house our React components.

  2. Container. This will house our Astro components.

In the src/ directory, you can also see the pages directory. The pages folder contains the pages of our app. The root page is the index.astro file.

In your container folder, create an Astro component, and name it movie.astro

---
---

<html lang="en">
    <body>
        <div class="">

        </div>  

    </body>
</html>

When you create the file, insert the line of code above. You now be wondering where our JS code will be written. Don't worry, I have your back.

In between the hyphens are where we will insert our code. For example,

---
const name: string = "Coding Pastor"
---

<html>
    <body>
        <div class="">
            <p>My name is {name} </p>
            <p>You see. Life Continues</p>
        </div>  

    </body>
</html>

To get the data for the movies, we are going to be using an API. Head over to https://www.themoviedb.org. Create an account. When your account has been created, go to your settings page to apply to get your API key.

Once you have been given an API key, visit the API documentation. This link should take you to the API we will be using. We won't be able to consume all the APIs, we would only be consuming one which is /movies/popular in this tutorial.

Let's get back to our codebase for now. We want to create a .env file where we will set our API keys and base URI. The .env file should be created in the base directory.

I am going to be using a dummy API_KEY for this tutorial. Please note that the API Key here is incorrect.

// your .env file
BASE_URI=https://api.themoviedb.org/3
API_KEY=123098Iamcodingpastor2345

We have successfully created our .env file. Let's head back to the movie.astro component we created.

---
const url: string = `${import.meta.env.BASEURI}/movies/popular?api_key=${import.meta.env.API_KEY}`
const response = await fetch(url)
const data = await response.json()
console.log(data)
---

From the piece of code above, we want to fetch the API to display the popular movies. If you check your terminal, you should see the data of popular movies being displayed.

In this format

When you look at the url too you can see we used import.meta.env instead of process.env . In Astro, when we want to get the environmental variables, we use import.meta.env

To continue, let's create a react component to display our data. We could have fetched everything on the movie.astro component but it is nicer to have a reusable component which will save us more time and fewer lines of code.

In the components directory, create a file and name it GetData.tsx This component will display our data. After creating it, we can add the following line of code.

import React from 'react'

type Props = {
    data: any
}

const GetData = ({ data }: Props) => {
    return (
        <main className='w-full'>
        <div className="px-4">
            {
        data?.results.map((item, index) => {
            return (
            <section key={index}>
            <a href={`${category}/${item.id}`}>
            <div  className='my-4 p-2'>
            <img className="rounded" 
                src={`https://image.tmdb.org/t/p/w500/${item.backdrop_path || 
                        item.profile_path || 
                        item.postal_path}`} alt="images" />

            <p className="border mt-2 border-slate-50 rounded-md hover:bg-    slate-500 w-fit p-1 text-xs">
                    Date: {item.release_date}
            </p>
            <p className='font-semibold text-lg my-2'>
                {item.title || item.original_name || item.name}
            </p>
            </div>
            </a>

            </section>
            )
        })
            }
        </div>
        </main>

    )
}

export default GetData

As we have said, the component above renders our data. Now let's insert this into our movie.astro component.

---
// import GetData
import GetData from '../../components/GetData'

const url: string = `${import.meta.env.BASEURI}/movies/popular?api_key=${import.meta.env.API_KEY}`
const response = await fetch(url)
const data = await response.json()
console.log(data)
---

<html>
    <body>
        <div class="">
           <GetData data={data} />
        </div>  
    </body>
</html>

Up till this point, this should be how our Astro component looks like. We are almost done. Now let's invite the movie.astro page to the index.astro page

In the index.astro page, import the movie.astro page. It can be in the format below

import Movie from '../container/movie.astro

After importing, we insert this page into the body of our page.

---
import Movie from '../container/movie.astro'
---

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
        <meta name="viewport" content="width=device-width" />
        <meta name="generator" content={Astro.generator} />
        <title>The Movie DB</title>
        <Navigation />


    </head>
    <body class="bg-slate-800 text-white">


        <section class="">
            <Movie />
        </section>
    </body>
</html>

Now let's see what we have done so far, to run your server use the command

npm run dev

Here we go!!

Conclusion

To recap, in this tutorial we talked about the basics of Astro, routing in Astro, dynamic routing in Astro, fetching APIs in Astro, and Using Astro with Reactjs.

You can check out the full version of the application here and please give it a star on GitHub here. Thank you.

I hope this article has been able to teach you how to start your Astro with React project and ideas. Thank you