Unlocking the Power of Static Site Generators with Capri

How Capri Works

Capri doesn’t ship any JavaScript to the frontend by default, instead relying on static HTML and CSS. To add interactivity and dynamic data, we use the *island.* suffix, which allows us to hydrate our components only when necessary.

// Example of using the *island.* suffix
// componentname.island.jsx
import React from 'react';

const ComponentName = () => {
  // Component code here
};

export default ComponentName;

Getting Started with Capri

To get started with Capri, we’ll create a new project using React. We can trigger a quickstart by running a simple command in our terminal, which sets up a sample Capri site.

# Create a new Capri project
npx capri init my-capri-project

# Move into the project directory
cd my-capri-project

# Start the development server
npm start

Building Our Blog

We’ll be building a Rick and Morty blog, where each post contains information about characters in the series. To start, we’ll create a Home.tsx file in our src folder, which will serve as the first page users see when they land on our blog.

// src/Home.tsx
import React from 'react';

const Home = () => {
  // Component code here
};

export default Home;

Displaying the List of Posts

Next, we’ll create a Posts component in a file called Posts.lagoon.tsx. We’ll loop through an array of ten items and display ten posts, each with a link that uses dynamic parameters to pass an ID to the page.

// src/Posts.lagoon.tsx
import React from 'react';

const Posts = () => {
  // Component code here
};

export default Posts;

Creating a Post Item Component

We’ll create a new component called PostItem.lagoon.tsx to display each post. We’ll retrieve the ID from the Posts.lagoon.tsx component and append it to our Rick and Morty endpoint.

// src/PostItem.lagoon.tsx
import React from 'react';
import axios from 'axios';

const PostItem = () => {
  // Component code here
};

export default PostItem;

Putting it All Together

Finally, we’ll import our PostItem.lagoon.tsx component into our App.tsx file as a route. We can now view our live demo and explore the code on GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *