These integration guides are not official documentation and the Strapi Support Team will not provide assistance with them.
Strapi is the leading open-source headless CMS offering features, like customizable APIs, role-based permissions, multilingual support, etc. It simplifies content management and integrates effortlessly with modern frontend frameworks.
Explore the Strapi documentation for more details.
React is a JavaScript library for building user interfaces, especially dynamic and interactive web applications. React lets you build user interfaces out of individual pieces called components.
Visit the React.js documentation for more.
The out-of-the-box Strapi features allow you to get up and running in no time: 1. Single types: Create one-off pages that have a unique content structure. 2. Draft and Publish: Reduce the risk of publishing errors and streamline collaboration. 3. 100% TypeScript Support: Enjoy type safety & easy maintainability 4. Customizable API: With Strapi, you can just hop in your code editor and edit the code to fit your API to your needs. 5. Integrations: Strapi supports integrations with Cloudinary, SendGrid, Algolia, and others. 6. Editor interface: The editor allows you to pull in dynamic blocks of content. 7. Authentication: Secure and authorize access to your API with JWT or providers. 8. RBAC: Help maximize operational efficiency, reduce dev team support work, and safeguard against unauthorized access or configuration modifications. 9. i18n: Manage content in multiple languages. Easily query the different locales through the API. 10. Plugins: Customize and extend Strapi using plugins.
Learn more about Strapi 5 feature.
We are going to start by setting up our Strapi 5 project with the following command:
🖐️ Note: make sure that you have created a new directory for your project.
You can find the full documentation for Strapi 5 here.
npx create-strapi-app@latest server
You will be asked to choose if you would like to use Strapi Cloud we will choose to skip for now.
Strapi v5.6.0 🚀 Let's create your new project
We can't find any auth credentials in your Strapi config.
Create a free account on Strapi Cloud and benefit from:
- ✦ Blazing-fast ✦ deployment for your projects
- ✦ Exclusive ✦ access to resources to make your project successful
- An ✦ Awesome ✦ community and full enjoyment of Strapi's ecosystem
Start your 14-day free trial now!
? Please log in or sign up.
Login/Sign up
❯ Skip
After that, you will be asked how you would like to set up your project. We will choose the following options:
? Do you want to use the default database (sqlite) ? Yes
? Start with an example structure & data? Yes <-- make sure you say yes
? Start with Typescript? Yes
? Install dependencies with npm? Yes
? Initialize a git repository? Yes
Once everything is set up and all the dependencies are installed, you can start your Strapi server with the following command:
cd server
npm run develop
You will be greeted with the Admin Create Account screen.
Go ahead and create your first Strapi user. All of this is local so you can use whatever you want.
Once you have created your user, you will be redirected to the Strapi Dashboard screen.
Since we created our app with the example data, you should be able to navigate to your Article collection and see the data that was created for us.
Now, let's make sure that all of the data is published. If not, you can select all items via the checkbox and then click the Publish button.
Once all your articles are published, we will expose our Strapi API for the Articles Collection. This can be done in Settings -> Users & Permissions plugin -> Roles -> Public -> Article.
You should have find
and findOne
selected. If not, go ahead and select them.
Now, if we make a GET
request to http://localhost:1337/api/articles
, we should see the following data for our articles.
🖐️ Note: The article covers (images) are not returned. This is because the REST API by default does not populate any relations, media fields, components, or dynamic zones.. Learn more about REST API: Population & Field Selection.
So, let's get the article covers by using the populate=*
parameter: http://localhost:1337/api/articles?populate=*
Nice, now that we have our Strapi 5 server setup, we can start to setup our React.js application.
In order to get started with React, you are recommended to start with a framework.
Scaffold a React app using the command below. The command below will scaffold a React application using the TypeScript template.
Use react
if you prefer plain JavaScript; otherwise, use react-ts
.
Learn more here
npm create vite@latest my-react-app -- --template react-ts
After running the command above, you will get the following response:
cd my-react-app
npm install
npm run dev
The command above will CD into your React application, install required dependencies and start your React applicaction on a Vite development server.
Your application should be available in the URL http://localhost:5173/
as shown below:
We will install Tailwind CSS as a PostCSS plugin.
Run the command below in your React project folder, in this case my-react-app
. The command below will install tailwindcss
, @tailwindcss/postcss
, and postcss
via npm.
npm install tailwindcss @tailwindcss/postcss postcss
Create a configuration file called postcss.config.cjs
at the root of your project and add the following code:
1// Path: ./postcss.config.cjs
2
3export default {
4 plugins: {
5 "@tailwindcss/postcss": {},
6 }
7}
Remove all the codes present inside your CSS file ./src/index.css
file and import Tailwind CSS.
1/* Path: ./src/index.css */
2
3@import "tailwindcss";
Make sure you are in your React application folder my-react-app
. Stop your React app and restart it using the command below:
npm run dev
Many HTTP clients are available, but on this integration page, we'll use Axios and Fetch.
Install Axios by running any of the commands below:
# npm
npm i axios
# yarn
yarn add axios
No installation needed
Execute a GET
request on the Article collection type in order to fetch all your articles.
Be sure that you activated the find
permission for the Article
collection type.
🖐️ NOTE: We want to also fetch covers (images) of articles, so we have to use the
populate
parameter as seen below.
1import axios;
2
3// fetch articles along with their covers
4const response = await axios.get("http://localhost:1337/api/articles?populate=*");
5console.log(response.data.data);
1const response = await fetch("http://localhost:1337/api/articles?populate=*");
2const data = await response.json();
3console.log(data.data);
In this project example, you will fetch data from Strapi and display them in your React.js application.
Head over to your React.js entry file ./src/App.tsx
to proceed. Ensure you remove all code snippet inside it.
Create a new component called App.
1export default function App() {
2 return <div className=" text-3xl text-red">App</div>;
3}
Import the React hooks useEffect
and useState
for side effects and state management, respectively.
1// Import React hooks
2import { useEffect, useState } from "react";
Create an interface called Article
, which represents the data structure of the articles we will fetch from Strapi. Also, create a Strapi URL constant.
1// Create Article Interface
2export interface Article {
3 id: string;
4 title: string;
5 content: string;
6 cover: any;
7 publishedAt: Date;
8}
9
10// Define Strapi URL
11const STRAPI_URL = "http://localhost:1337";
articles
State VariableInside the App component, create a state variable articles
to hold articles data fetched from Strapi.
1// Define articles state
2const [articles, setArticles] = useState<Article[]>([]);
Create an asynchronous function that fetches the articles from the Strapi API. The data fetched is passed to setArticles
to update the articles state.
1// fetch articles
2const getArticles = async () => {
3 const response = await fetch(`${STRAPI_URL}/api/articles?populate=*`);
4 const data = await response.json();
5 setArticles(data.data);
6};
Create a helper function to format the publishedAt
date of the article into a human-readable format (MM/DD/YYYY)
.
1// Format date
2const formatDate = (date: Date) => {
3 const options: Intl.DateTimeFormatOptions = {
4 year: "numeric",
5 month: "2-digit",
6 day: "2-digit",
7 };
8 return new Date(date).toLocaleDateString("en-US", options);
9};
Use the useEffect
hook to run the getArticles
function when the component mounts.
1useEffect(() => {
2 getArticles();
3}, []);
Render and display the fetched articles from Strapi.
1return (
2 <div className="p-6">
3 <h1 className="text-4xl font-bold mb-8">React.js and Strapi Integration</h1>
4 <div>
5 <h2 className="text-2xl font-semibold mb-6">Articles</h2>
6 <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
7 {articles.map((article) => (
8 <article
9 key={article.id}
10 className="bg-white shadow-md rounded-lg overflow-hidden"
11 >
12 <img
13 className="w-full h-48 object-cover"
14 src={STRAPI_URL + article.cover.url}
15 alt={article.title}
16 width={180}
17 height={38}
18 />
19 <div className="p-4">
20 <h3 className="text-lg font-bold mb-2">{article.title}</h3>
21 <p className="text-gray-600 mb-4">{article.content}</p>
22 <p className="text-sm text-gray-500">
23 Published: {formatDate(article.publishedAt)}
24 </p>
25 </div>
26 </article>
27 ))}
28 </div>
29 </div>
30 </div>
31);
Now, this is what your React.js project should look like:
Awesome, congratulations!
You can find the complete code for this project in the following Github repo.
If you have any questions about Strapi 5 or just would like to stop by and say hi, you can join us at Strapi's Discord Open Office Hours Monday through Friday at 12:30 pm - 1:30 pm CST: Strapi Discord Open Office Hours
For more details, visit the Strapi documentation and React.js documentation.