Strapi is a free and open-source headless CMS that makes it easy to build and manage APIs. In this tutorial, we’ll be building a full-stack app with Strapi and React.
- Setting Up Strapi
To get started, you need to have Node.js and npm installed on your machine. Then, you can install Strapi by running the following command:
npm install strapi@beta -g
Once Strapi is installed, you can create a new project by running the following command:
strapi new my-app
After creating your project, navigate to the project directory and start the server:
cd my-app
strapi start
You should now be able to access the Strapi admin panel at http://localhost:1337/admin
.
- Defining Your API
In the Strapi admin panel, you can define your API by creating content types and setting up relationships between them. For this tutorial, we’ll create a simple blog that has posts and comments.
To create a new content type, go to the Content-Types Builder
section and click on the Create a new content type
button. Fill in the form with the following information:
- Content Type Name: Post
- Description: Blog posts
Next, add some fields to your Post content type. We’ll start with a title and a body.
- Building the Front-end with React
Now that we have our API set up, we can start building the front-end with React. We’ll use create-react-app
to set up a new React app.
First, create a new React app by running the following command:
npx create-react-app my-app-client
Next, navigate to the my-app-client
directory and install the necessary dependencies:
cd my-app-client
npm install axios react-router-dom
Now that we have our dependencies installed, let’s start building the app.
- Retrieving Data from the API
We’ll start by retrieving the data from the Strapi API and displaying it in our React app. We’ll use the axios
library to make HTTP requests to the Strapi API.
First, create a new file called api.js
in the src
directory and add the following code:
import axios from 'axios';
export default axios.create({
baseURL: 'http://localhost:1337'
});
Next, create a new component called Posts.js
and add the following code:
import React, { useState, useEffect } from 'react';
import api from './api';
function Posts() {
const [posts, setPosts] = useState([]);
useEffect(() => {
async function fetchData() {
const response = await api.get('/posts');
setPosts(response.data);
}
fetchData();
}, []);
return (
<div>
{posts.map(post => (
<div key