React Dev

React Dev

1675656264

Build a Full Stack E-Commerce Website with React 18, Strapi & Stripe

Build a complete ecommerce website from scratch, In this video we will cover all important topics of react js such as jsx, components, props, state,  lifecycle of components, conditional rendering, lists, keys, context api & more. At the end of this tutorial you would have a fully functional ecommerce website which you can use for your own business or you can sell out if to the others.

In this tutorial you’ll learn:
- React 18 and its latest features
- React functional components and their reusability
- React hooks and state management
- How to use Context API
- Advance concepts or Context API
- Rapid UI building with SCSS
- Most important concepts of SCSS
- Mobile first responsive approach
- How to use Strapi Headless CMS
- CRUD Operations in Strapi
- Functional Programming through utility methods
- How to use Axios in react app
- How to integrate Stripe payment gateway

👇 Time Stamps
00:00:00 Intro & Project Demo
00:03:58 Project Setup & Walkthrough of Folder Structure
00:08:39 React Router DOM Setup
00:19:21 Header Section
00:58:05 Homepage Hero Banner Section
01:19:38 Newsletter Section
01:34:35 Footer Section
01:59:28 Homepage Popular Products Section
02:13:58 Category Page
02:23:16 Product Details Page
02:49:04 Related Products for Product Details Page
02:52:07 Shopping Cart
03:30:35 Search Product Modal
03:50:22 Strapi Integration & Walkthrough
04:06:00 API Testing 
04:17:20 API Setup for Homepage Categories & Products Section 
04:28:17 Homepage Categories API Integration 
04:31:24 Homepage Products API Integration 
04:34:40 Category Page API Integration
04:52:53 Product Details Page API Integration
05:12:28 Product Details Page Related Products API Integration
05:17:17 Shopping Cart Functionality
05:50:03 Live Search Functionality
05:59:20 Stripe Payment Gateway Integration

⭐ React - https://reactjs.org/docs/getting-started.html 
⭐ Strapi - https://strapi.io/ 
⭐ Stripe - https://stripe.com/en-in 

📚 Materials/References:
GitHub Repository Client (give it a star ⭐): http://bit.ly/3hBeEjc 
GitHub Repository Api (give it a star ⭐): http://bit.ly/3v12SSo 
Gist: http://bit.ly/3jfyZuU 
Assets: http://bit.ly/3jcQYlD 
Products: http://bit.ly/3FOpUAy 

Installed NPM Packages:
Axios - https://www.npmjs.com/package/axios-react 
React Router DOM - https://www.npmjs.com/package/react-router-dom 
React Icons - https://www.npmjs.com/package/react-icons 

Download node 16 LTS version: https://drive.google.com/file/d/1CbEP6fQHqLLKgPMm-7yabGnwNyHagayn/view?usp=sharing 

Subscribe: https://www.youtube.com/@jsdevhindi/featured 

#react #javascript #strapi #stripe 

Build a Full Stack E-Commerce Website with React 18, Strapi & Stripe
Web  Dev

Web Dev

1669435680

Full Stack Ecommerce App with React, Strapi and Stripe

In this Shopping App tutorial, you'll learn how to build and deploy a full-stack E-commerce App with React, Strapi and Stripe. Full-stack React e-commerce app tutorial for beginners.


00:00 Introduction
05:36 Installation  
07:12 React Router Dom v6.4 Tutorial
14:05 React Navbar Design
25:46 React Footer Design
32:11 React Slider Tutorial (without any library)
44:00 Featured Products and Product Card Design
55:21 Grid System Using CSS Flexbox
01:09:13 React Product List Page Design
01:21:07 React Single Product Page Design
01:34:00 React Shopping Cart Design
01:43:15 Strapi Tutorial for Beginners
01:56:20 React Strapi E-commerce App (Connection)
02:07:56 React Strapi E-commerce App (Fetching Items)
02:17:35 React Strapi Rest Api Filtering Tutorial
02:28:35 React E-commerce Fetch a Single Product
02:31:26  React Redux Shopping Cart Tutorial
02:27:40 React Redux Toolkit How to Persist State
02:50:05 Strapi Stripe Payment Using a React App
03:11:40 How to Deploy React app to a Shared Hosting?
03:13:22 How to Deploy Strapi app to a VPS Server?
03:30:15 Outro

Source Code:

https://github.com/safak/youtube2022/tree/e-commerce  ( Coming soon (updating files) )

Deployment source:

https://github.com/safak/youtube/tree/mern-deployment

#react #strapi #stripe #programming #developer #morioh #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment 

Full Stack Ecommerce App with React, Strapi and Stripe

A Boilerplate for Building Applications using Strapi and Next.js

This is a boilerplate for building applications using Strapi and Next.js. This boilerplate consists of the following:

  1. frontend: Next.js application
  2. backend: Dockerized Strapi application
  • Overview
  • Requirements
  • Packages
    • 1. Frontend: Next.js application
    • 2. Backend: Dockerized Strapi application
  • Installation
    • 1. Clone the application
    • 2. Install necessary dependencies for the frontend application
    • 3. Create a .env file and copy the contents from .env.example (present in frontend directory)
    • 4. Start the frontend application
    • 5. Go inside the directory of the backend package on another terminal window
    • 6. Start docker-compose
  • Deployment
    • Frontend application
    • Backend application
  • Other interesting repositories
  • License

Overview

This boilerplate is built using the following technologies:

  1. Chakra UI
  2. Emotion
  3. GraphQL
  4. Apollo
  5. NextAuth
  6. TypeScript

It supports GraphQL Query and Mutation out of the box.

Requirements

  1. Node.js
  2. npm
  3. Docker

Packages

1. Frontend: Next.js application

This application is the primary user-facing application. Once it’s up and running (see Development section), it’s available on http://localhost:3000/.

2. Backend: Dockerized Strapi application

Strapi is the leading open-source headless CMS. It’s 100% Javascript, fully customizable and developer-first.

Installation

1. Clone the application

git clone https://github.com/ghoshnirmalya/nextjs-strapi-boilerplate

2. Install necessary dependencies for the frontend application

cd frontend && yarn install

3. Create a .env file and copy the contents from .env.example (present in frontend directory)

We might need to run the following command:

source .env

4. Create and copy the Google client credentials

Create a new Google OAuth Client and copy the credentials (Client ID and Client Secret) in your .env file.

5. Start the frontend application

From the frontend directory, we can run the following command to start our Next.js frontend application:

yarn dev

The above command will start the frontend application on http://localhost:3000/.

6. Go inside the directory of the backend package on another terminal window

cd backend

7. Start docker-compose

docker-compose up

We need to start Docker and then run the above command which will change the current directory to the backend package’s directory and then start the backend package. If everything goes well, it’ll be up and running on http://localhost:1337/graphql.

8. Configure Strapi

a. Allow permissions for all operations on the Feed content-type for Authenticated users.

Authenticated user role

Allow permissions for all operations on the Feed content-type for Authenticated users

b. Allow permissions for all operations on the Feed content-type for Authenticated users as well.

Allow permissions for all operations on the Feed content-type for Authenticated users as well

c. Enable the Google provider.

Enable the Google provider

Enable informations for the Google provider

d. Click on the "Done" button and now we can log into our Next.js application using our Google account.

Deployment

Frontend application

Click on the button below to deploy the frontend application on Vercel. You'll need to sign up for a free Vercel account.

Deploy with Vercel

Backend application

We're still working on it.

Other interesting repositories

  1. Hasura Next.js Boilerplate
  2. Hasura Next.js Trello Clone
  3. React Search Box
  4. LinkedIn Clone using Create React App

Download details:

Author: ghoshnirmalya
Source code: https://github.com/ghoshnirmalya/nextjs-strapi-boilerplate
License: MIT license

#nextjs #react #reactjs #javascript #strapi

A Boilerplate for Building Applications using Strapi and Next.js
Hoang  Kim

Hoang Kim

1659443361

Cách Xây Dựng Cửa Hàng Thương Mại điện Tử Của Bạn Bằng Gatsby & Strapi

Tìm hiểu cách tạo cửa hàng thương mại điện tử Jamstack bằng Gatsby và Strapi. Chúng tôi sẽ xây dựng một cửa hàng giày trực tuyến với cách tiếp cận từng bước.

Hãy bắt đầu với một câu hỏi: Khi xây dựng một trang web hoặc ứng dụng trong thời đại ngày nay, những điều chính chúng ta cần xem xét là gì?

Có rất nhiều câu trả lời tiềm năng cho câu hỏi này, nhưng speed, costsecuritynên làm nổi bật bất kể chúng tôi đang xây dựng cái gì. Cho dù đó là một trang blog, trang web cá nhân hay cổng thương mại điện tử, người dùng của chúng tôi sẽ mong đợi nó tải nhanh, duy trì và bảo mật không tốn kém cho người dùng cuối.

Rất may, kiến ​​trúc Jamstack có thể giúp chúng tôi trên cả ba khía cạnh.

Jamstack cho phép chúng tôi xây dựng các trang web tĩnh bằng cách sử dụng các đánh dấu dựng sẵn, API không máy chủ… thậm chí cả dữ liệu từ CMS. Các trang web tĩnh này nhanh hơn so với lựa chọn thay thế, vì các đánh dấu được tạo sẵn và phân phát an toàn từ một CDN bảo mật (thay vì máy chủ gốc).

Và có cả một hệ sinh thái công nghệ hỗ trợ việc tạo các ứng dụng Jamstack. Trong bài viết này, chúng tôi sẽ đề cập đến hai công nghệ nổi tiếng nhất trong số những công nghệ này: GatsbyStrapi.Chúng tôi sẽ sử dụng chúng để xây dựng một ứng dụng Thương mại điện tử - một cửa hàng giày trực tuyến được gọi là shoes.Original, đúng không?

Gatsby và Strapi

Gatsby là một trình tạo trang web tĩnh dựa trên React được thiết kế đặc biệt để tạo các đánh dấu dựng sẵn và cung cấp một nền tảng đám mây thống nhất để xây dựng, xem trước và lưu trữ các ứng dụng của bạn. Nó siêu nhanh, dễ dàng tích hợp với nhiều nguồn dữ liệu khác nhau và đi kèm với rất nhiều hệ sinh thái plug-in.

Mặt khác, Strapi là một ứng dụng mã nguồn mở, có khả năng tùy biến cao giúp bạn xây dựng các API nhanh hơn và quản lý nội dung của mình một cách dễ dàng. Bất kỳ ứng dụng khách front-end nào cũng có thể sử dụng các API bằng REST hoặc GraphQL và bạn có thể tự lưu trữ ứng dụng Strapi một cách dễ dàng trên một nhà cung cấp như Heroku.

Hai chương trình kết hợp hoàn hảo với nhau: trong khi Gatsby cung cấp giao diện người dùng nhanh hơn, Strapi giải quyết nhu cầu về hệ thống quản lý nội dung và kho dữ liệu phía sau (CMS).

Được rồi, bây giờ bạn đã biết Gatsby và Strapi có thể cung cấp những gì, hãy xem cách chúng hoạt động trong thực tế bằng cách xây dựng shoesứng dụng.

Bắt đầu với shoesứng dụng

Chúng tôi sẽ chia shoesứng dụng thành hai phần chính:

  1. datastore: Điều này yêu cầu Strapidự án, với tất cả nội dung và API cần thiết cho ứng dụng.
  2. client: Điều này dựa vào Gatsbydự án sử dụng các API, với sự trợ giúp của GraphQL, để tìm nạp nội dung từ Strapi và hiển thị nội dung đó trong các giao diện người dùng đẹp mắt.

Đầu tiên, chúng tôi sẽ thiết lập datastorebằng cách sử dụng Strapi. Xin lưu ý rằng bạn phải cài đặt Node.js để chạy ứng dụng cục bộ. Bạn cũng có tùy chọn cài đặt sợi , nhưng nếu bạn không có sợi, vui lòng sử dụng npmthay thế.

Việc datastoresử dụngStrapi

Strapi cung cấp một loạt các mẫu để bắt đầu ứng dụng một cách nhanh chóng. Vì cửa hàng giày của chúng tôi là một ứng dụng thương mại điện tử, chúng tôi sẽ sử dụng ecommercemẫu để tạo datastore.

Để thực hiện việc này, chỉ cần tạo một shoesthư mục và mở dấu nhắc lệnh (hoặc thiết bị đầu cuối) trên thư mục giày.

Bây giờ, sử dụng lệnh sau để tạo một dự án Strapi:

yarn create strapi-app datastore --template ecommerce

Xin lưu ý rằng chúng tôi đã cung cấp tên dự án datastorevà mẫu như ecommercetrong lệnh trên.

Lệnh sẽ mất một lúc để tải xuống các phụ thuộc cần thiết, cài đặt chúng và thiết lập chúng cho bạn. Tuy nhiên, sau khi hoàn tất, ứng dụng Strapi sẽ có thể truy cập được trên trình duyệt của bạn bằng cách sử dụng URL [localhost:1337](http://localhost:1337).

Điều quan trọng cần nhớ là bạn cần đăng ký hồ sơ của mình lần đầu tiên để tạo thông tin đăng nhập. Những thông tin đăng nhập tương tự này sẽ được sử dụng để xác thực trong Strapi, vì vậy vui lòng dành thời gian để điền vào các chi tiết bắt buộc và đăng ký.

1-strapi-initial.png

Sau khi đăng ký, bạn sẽ đến trang chào mừng của Strapi. Điều này sẽ cung cấp cho bạn các gợi ý hướng dẫn bạn cần để tạo cấu trúc nội dung, tham gia cộng đồng và hoàn thành nhiều chức năng khác.

2-admin-panel.png

Tạo các loại

Bây giờ chúng ta sẽ bắt đầu tạo typestrong Strapi. Bạn có thể coi các loại này như là các bảng có lược đồ trong cơ sở dữ liệu quan hệ.

Đối với ứng dụng của chúng tôi, chúng tôi muốn tạo dữ liệu giày dưới dạng một Productloại. Mỗi sản phẩm giày sẽ có thông tin meta riêng, như tên, giá cả, mô tả, cổ phiếu, danh mục và công ty.

Chúng tôi cũng sẽ quản lý CategoryCompanyvới tư cách là các loại độc lập, và tạo mối quan hệ với Productloại.

Vì vậy, chúng ta hãy bắt đầu tạo từng loại một. Đầu tiên, hãy tạo các trường sau cho Categoryloại:

  • name : Một trường kiểu văn bản.
  • slug : một phân đoạn URL để xác định danh mục này. Nó thuộc loại UID

Ảnh chụp màn hình 2022-07-14 lúc 9.22.40 PM.png

Tương tự, bạn có thể tạo loại Công ty với các trường tên và slug.

Ảnh chụp màn hình 2022-07-14 lúc 9.49.27 PM.png

Và bây giờ chúng ta sẽ tạo Loại sản phẩm, với các trường được hiển thị trong hình dưới đây.

Ảnh chụp màn hình 2022-07-04 lúc 3.55.56 PM.png

Hầu hết các trường ở trên là tự giải thích. Tuy nhiên, một số lĩnh vực cần giải thích.

  • hình ảnh : Điều này đề cập đến hình ảnh của sản phẩm và loại Media. Trong Strapi, bạn có thể tải nội dung (hình ảnh, video, tệp) lên thư viện phương tiện để sử dụng sau này.
  • danh mụccông ty liên quan đến các loại tương ứng mà chúng tôi đã tạo.
  • trạng thái : Một trường cho biết trạng thái của sản phẩm.
  • cổ phiếu : Một trường số giữ bản ghi số lượng giày trong kho.

Chèn dữ liệu

Vì tất cả các kiểu bắt buộc hiện đã được tạo, chúng ta có thể bắt đầu tạo dữ liệu mẫu trong Strapi. Đầu tiên, chúng ta hãy tải lên một số hình ảnh giày mát mẻ. Bạn có thể thu thập chúng từ một trang web truyền thông như unsplashvà tải lên các mục từ Media Librarymenu.

Ảnh chụp màn hình 2022-07-04 lúc 3.56.38 PM.png

Tiếp theo, duyệt qua tùy chọn Trình quản lý nội dung từ điều hướng bên trái và bắt đầu tạo các mục nhập cho loại Danh mục. Bạn có thể tạo các danh mục được đề cập trong hình ảnh bên dưới hoặc thoải mái tạo danh mục của riêng bạn.

Ảnh chụp màn hình 2022-07-04 lúc 3.57.05 PM.png

Tương tự, hãy chèn các mục nhập cho dữ liệu Công ty.Ảnh chụp màn hình 2022-07-04 lúc 3.57.22 PM.png

Cuối cùng, nhập dữ liệu cho Loại sản phẩm.

Ảnh chụp màn hình 2022-07-04 lúc 4.07.19 PM.png

Mã thông báo API

Cho đến nay, chúng tôi đã tạo tất cả nội dung bắt buộc trong Strapi và sắp sử dụng tất cả các phần tử trong giao diện người dùng, với các API của Strapi. Bạn có thể truy cập các API Strapi bằng cách sử dụng REST đến GraphQL, nhưng hãy nhớ rằng bạn cần lấy Mã thông báo API để thực hiện các lệnh gọi API thành công.

Nhấp vào Cài đặt> Cài đặt chung> Mã thông báo API từ thanh điều hướng bên trái và nhấp vào Create new API Tokennút để tạo mã thông báo toàn quyền truy cập cho ứng dụng giày. Vui lòng giữ mã thông báo này an toàn với bạn, vì chúng tôi sẽ sớm sử dụng mã thông báo này.

Ảnh chụp màn hình 2022-07-04 lúc 4.07.45 PM.png

Việc clientsử dụngGatsby

Chúng tôi đã thiết lập thành công datastorevới Strapi, và bây giờ đã đến lúc thiết lập clientbên với Gatsby.

Để làm như vậy, hãy mở một dấu nhắc lệnh / thiết bị đầu cuối khác tại thư mục gốc của dự án và thực hiện lệnh sau.

yarn global add gatsby-cli

Lệnh này sẽ cài đặt Giao diện dòng lệnh Gatsby (CLI) trên toàn cầu. Điều này giúp chúng tôi tương tác với khung Gatsby để thực hiện các tác vụ khác nhau.

Cũng giống như Strapi, Gatsby đi kèm với một số mẫu để tạo một dự án. Trong thế giới Gatsby, chúng được gọi là 'mẫu khởi động'. Chúng tôi sẽ sử dụng mẫu khởi động mặc định để tạo dự án và đặt tên client.

Vui lòng thực hiện lệnh sau để tạo dự án Gatsby.

npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default

Lệnh trên sẽ mất một lúc và tạo cấu trúc dự án cho bạn. Bây giờ thay đổi thư mục clientvà khởi động ứng dụng cục bộ bằng gatsby developlệnh.

cd client
gatsby develop

Ứng dụng Gatsby sẽ chạy trên [localhost:8000](http://localhost:8000)URL và bạn sẽ thấy giao diện người dùng như thế này khi truy cập bằng trình duyệt của mình. Đó là một trang mặc định từ mẫu ban đầu mà chúng tôi đã sử dụng. Chúng tôi sẽ thay đổi nó sớm.

Ảnh chụp màn hình 2022-07-04 lúc 4.28.49 PM.png

Gatsby and Strapi: A Better Together Story

Vì vậy, bây giờ chúng tôi sẽ kết hợp Gatsby và Strapi lại với nhau để tạo hình dạng cho ứng dụng của chúng tôi. Chúng tôi sẽ gọi các API Strapi từ Gatsby và tìm nạp dữ liệu giày tại thời điểm xây dựng.

Hệ sinh thái trình cắm thêm Gatsby có một trình cắm thêm nguồn được gọi là gatsby-source-strapigiúp tìm nạp dữ liệu từ Strapi bằng cách sử dụng GraphQL. Hãy cài đặt plug-in đó và một số phụ thuộc khác để xử lý hình ảnh và chuyển đổi. Vui lòng thực hiện lệnh sau từ thiết bị đầu cuối trong thư mục client.

yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp

Tạo một tệp được gọi là thư mục .env.developmentgốc client, với nội dung sau.

STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337

Đây <STRAPI-API-TOKEN>là mã thông báo bạn đã sao chép trong khi thiết lập kho dữ liệu Strapi. Bây giờ bạn có thể nhập clientdự án trong trình soạn thảo mã yêu thích của mình (như Mã VS trong trường hợp của tôi).

Bây giờ, hãy mở gatsby-config.jstệp và thay thế nội dung bằng nội dung bên dưới. Đây là tệp cấu hình xác định siêu dữ liệu của trang web và các tùy chọn trình cắm.

Hãy xem xét kỹ hơn các tùy chọn mà chúng tôi đã xác định cho gatsby-source-strapitrình cắm: chúng tôi đã chỉ định URL API Strapi, Mã thông báo API và tên của các loại bộ sưu tập mà chúng tôi muốn tương tác.

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  siteMetadata: {
    title: `Shoes`,
    description: `The one stop shop for your shoes and footwear needs.`,
    author: `@tapasadhikary`,
    siteUrl: `https://shoes.io/`,
  },
  plug-ins: [
    "gatsby-plugin-gatsby-cloud",
    {
      resolve: "gatsby-source-strapi",
      options: {
        apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
        accessToken: process.env.STRAPI_TOKEN,
        collectionTypes: [
          {
            singularName: "product",
          },
          {
            singularName: "company",
          },
          {
            singularName: "category",
          },
        ],
      },
    },
    "gatsby-plugin-image",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    "gatsby-transformer-remark",
  ],
}

Vui lòng dừng và khởi động lại gatsby developchức năng và truy cập URL http://localhost:8000/__graphqlđể mở trình khám phá GraphQL của Gatsby.

Gatsby cung cấp trình khám phá GraphQL như một công cụ dành cho nhà phát triển, vì vậy bạn có thể xây dựng các truy vấn GraphQL một cách dễ dàng. Bạn nên tìm tất cả các loại bộ sưu tập Strapi từ Explorercột ngoài cùng bên trái: tất cả chúng đều bắt đầu bằng văn bản allStrapi.

Được rồi, bây giờ chúng ta hãy thử tạo một truy vấn mẫu cho allStrapiProductbộ sưu tập. Bạn có thể mở rộng bộ sưu tập và chọn các trường mà bạn muốn tìm nạp dữ liệu; bạn sẽ thấy một truy vấn GraphQL được tạo tự động, dựa trên lựa chọn của bạn.

Bây giờ bạn có thể chạy truy vấn bằng cách nhấn vào nút 'chạy' trong tiêu đề của bảng điều khiển ở giữa. Bạn có thể tìm thấy đầu ra ở bảng ngoài cùng bên phải.

Tôi khuyên bạn nên dành một chút thời gian với trình khám phá GraphQL và thử với các truy vấn để làm quen với nó.

Ảnh chụp màn hình 2022-07-04 lúc 4.36.51 PM.png

Để xây dựng các truy vấn GraphQL, chúng tôi sẽ sử dụng chúng để tạo các thành phần giao diện người dùng. Gatsby dựa trên React, vì vậy bạn có thể sử dụng toàn bộ sức mạnh của thư viện React trong Gatsby. Chỉ cần mở index.jstệp và thay thế nội dung hiện có bằng mã sau.

// index.js

import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"

import { useStaticQuery, graphql } from "gatsby"

import '../style/shoes.css'

const IndexPage = () => {
  const { allStrapiProduct } = useStaticQuery(graphql`
    query {
      allStrapiProduct(sort: {order: ASC, fields: title}) {
        edges {
          node {
            image {
              url
            }
            slug
            price
            title
            id
            stock
            status
          }
        }
      }
    }
  `)

  return (
    <Layout>
      <Seo title="Home" />
        <ShoeList shoes={allStrapiProduct.edges} />
    </Layout>
  )
}

export default IndexPage

 

Bây giờ chúng ta hãy đi sâu vào mã trong index.jstệp. Chúng tôi sử dụng truy vấn GraphQL để tìm nạp tất cả các sản phẩm được sắp xếp theo tiêu đề sản phẩm theo thứ tự tăng dần. Gatsby cung cấp cho chúng ta một móc React được gọi useStaticQueryđể thực hiện truy vấn GraphQL.

Tiếp theo, chúng ta chuyển mảng sản phẩm đã tìm nạp (giày) làm chỗ dựa cho ShoeListthành phần. Chúng ta cần tạo thành phần sẽ lặp lại trên shoesmảng và bắt đầu tạo bố cục thẻ cho từng chi tiết giày.

Để thực hiện việc này, vui lòng tạo một tệp có tên ShowList.jsdưới componentsthư mục với nội dung sau.

// ShoeList.js

import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
  console.log(shoes);
  return (
    <div className="shoe-list">
    {shoes.map((shoe) => (
      <ShoeCard key={shoe.node.id} shoe={shoe.node} />
    ))}
    </div>
  )


}

export default ShoeList

 

Như bạn nhận thấy trong đoạn mã trên, chúng tôi lấy ra từng chi tiết giày và chuyển chúng làm đạo cụ cho một thành phần khác, ShoeCard. Vì vậy, bạn cần tạo một tệp có tên ShoeCard.jsdưới componentsthư mục, với nội dung như sau.

// ShoeCard.js

import * as React from "react"
import { Link } from "gatsby"

const ShoeCard = ({ shoe }) => {
  return (
    <Link
      to={`/${shoe.slug}`}
      className="shoe-card" >
        <div className="img-container">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>  
        <div className="details">
          <h2>{shoe.title} - ${shoe.price}</h2>
        </div>
    </Link>
  )
}

export default ShoeCard

 

Thành phần ShoeCard hiển thị hình ảnh, tiêu đề và giá của giày. Sau đó, chúng tôi sẽ chỉ tiết lộ tiêu đề và giá khi người dùng di chuột qua hình ảnh chiếc giày bằng các kiểu CSS.

Ngoài ra, hãy lưu ý rằng thẻ giày được bọc bằng a Link. Thành phần Liên kết đến từ Gatsby và giúp chúng tôi liên kết giữa các trang trong ứng dụng Gatsby. Thành phần Liên kết có một thuộc tính mà chúng tôi sử dụng để liên kết đến trang đích. Trong ví dụ trên, giá trị thuộc tính là giá trị slug của mỗi chiếc giày.

Chúng tôi dự định chuyển sang một trang mới khi người dùng nhấp vào thẻ giày; trang mới này sẽ hiển thị thêm chi tiết về một đôi giày và các tùy chọn mua. Nhưng chúng tôi cần thực hiện một số thay đổi và chúng tôi sẽ thực hiện điều đó sau. Đầu tiên, chúng ta cần tập trung vào việc chuẩn bị trang danh sách giày với tất cả các kiểu dáng.

Hãy tinh chỉnh Bố cục và các thành phần Header một chút. Đầu tiên, thay thế nội dung của layout.jstệp bằng nội dung sau. Nó khá giống với tệp layout.js hiện có đi kèm với mẫu, nhưng chúng tôi đã thực hiện một số chỉnh sửa nhỏ về kiểu dáng.

// layout.js

import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"

import Header from "./header"
import "./layout.css"

const Layout = ({ children }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)

  return (
    <>
      <Header siteTitle={data.site.siteMetadata?.title || `Title`} />
      <div className="container">
        <main className="content">{children}</main>
        <footer>
          © {new Date().getFullYear()} &middot; Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
        </footer>
      </div>
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

 

Đây là nội dung của Header.jstệp bạn cần thay thế trong tệp hiện có.

// Header.js

import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"

const Header = ({ siteTitle }) => (
  <header>
    <Link to="/" className="logo">
    👠 {siteTitle}
    </Link>
  </header>
)

Header.propTypes = {
  siteTitle: PropTypes.string,
}

Header.defaultProps = {
  siteTitle: ``,
}

export default Header

Bây giờ, chúng ta hãy tạo một stylethư mục trong thư mục src. Để làm như vậy, hãy tạo một shoes.csstệp trong stylethư mục với nội dung sau.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");

*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  scroll-behavior: smooth;
}
html {
  overflow: auto;
}

body {
  height: 100vh;
  background-color: rgb(3, 28, 34);
  color: #ffffff;
  font-family: "Poppins", sans-serif;
}

a {
  text-decoration: none;
  color: #ffffff;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #282d2e;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  margin: 0 0 0.5rem 0;
}

header .logo {
  font-size: 2rem;
  font-weight: 500;
  color: #ffffff;
  padding: 0.5rem;
}

footer {
  width: 100%;
  padding: 0.3rem;
  background-color: #282d2e;
  text-align: center;
}

footer > a {
  color: #1af41a;
  text-decoration: underline;
}

.btn {
  padding: 10px;
  cursor: pointer;
  font-size: 18px;
  border: none;
  border-radius: 10px;
}

.btn.btn-primary {
  background-color: #40ee10;
  color: #000000;
}

.btn.btn-primary:hover {
  background-color: #70e007;
  color: #000000;
}

.btn.btn-secondary {
  background-color: #ffffff;
  color: #282d2e;
}

.btn.btn-secondary:hover {
  background-color: #282d2e;
  color: #ffffff;
}

.container {
  height: calc(100vh - 73px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content {
  flex-grow: 1;
  overflow: auto;
}

.shoe-list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.shoe-card {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  width: 15rem;
  height: 15rem;
  margin: 1.2rem;
}

.shoe-card .img-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  transition: all 0.5s ease-in-out;
}

.shoe-card .img-container > IMG {
  width: 15rem;
  height: 15rem;
  object-fit: cover;
  resize: both;
  border-radius: 10px;
}

.shoe-card:hover .img-container {
  transform: translate(-1rem, -1rem);
}

.shoe-card:hover .details {
  transform: translate(1rem, 1rem);
}

.shoe-card .details {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 0.5rem;
  display: flex;
  background-color: #fff;
  z-index: 1;
  align-items: flex-end;
  transition: 0.5s ease-in-out;
  line-height: 1rem;
  border-radius: 10px;
}

.shoe-card .details h2 {
  display: block;
  font-size: 1rem;
  color: #000000;
  font-weight: 500;
}

Và… đó là nó!

Bây giờ chạy ứng dụng cục bộ bằng cách sử dụng URL [http://localhost:8000](http://localhost:8000)và bạn sẽ thấy danh sách hình ảnh chiếc giày trên trang. Di chuột qua các hình ảnh giày và một hình ảnh động sẽ hiển thị tên giày và giá.

shoe-list.png

Thật tuyệt. Vì vậy, bây giờ, hãy thử nhấp vào bất kỳ thẻ giày nào.

Oái oăm! bạn nhận được một trang như dưới đây, và nó có vẻ bị hỏng. Nó đã cố gắng điều hướng đến một trang được xác định bởi giá trị slug của chiếc giày, nhưng không thành công.

Nhưng đừng lo lắng, chúng tôi có thể khắc phục sự cố.

Ảnh chụp màn hình 2022-07-11 lúc 9.44.03 PM.png

Gatsby có thể tạo các trang tại thời điểm xây dựng bằng cách sử dụng các mẫu. Các cấu trúc này khai thác cùng một cấu trúc giao diện người dùng mà bạn muốn sử dụng cho một tập dữ liệu khác.

Ví dụ: trong shoesứng dụng của chúng tôi, chúng tôi muốn hiển thị chi tiết của từng đôi giày. Cấu trúc trang chi tiết sẽ giống nhau, nhưng dữ liệu về giày sẽ thay đổi tùy thuộc vào hình ảnh giày mà chúng ta đang nhấp vào.

Vì vậy, chúng ta có thể tạo một mẫu có tên shoe-details.jsdưới src/templatesthư mục với nội dung như sau.

// shoe-details.js

import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"

export default function ShoeDetails({ data }) {
  const shoe = data.strapiProduct
  const [quantity, setQuantity] = useState(1)
  return (
    <Layout>
      <div className="shoe-details">
        <div className="cover">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>
        <div className="info">
          <div className="info-heading">
            <h2>{shoe.title}</h2> 
            <Link to={`/category/${shoe.categories[0].slug}`}>
              <span>{shoe.categories[0].name}</span>
            </Link> { ' '}
            from {' '}
            <Link to={`/company/${shoe.company.slug}`}>
              {shoe.company.name}
            </Link>
          </div>

          <div className="info-body">
            <p>{shoe.description}</p>
            <span>${shoe.price} per unit</span> { ' - '}
            <>
              {
                shoe.stock > 0 ?
                  <span>{shoe.stock} In Stock</span> :
                  <span>Out of Stock</span>
              }
            </>
          </div>

          <div className="info-purchase">
            {
              shoe.stock > 0 ?
              <>
                <p>
                  I want to purchase {' '}
                  <input 
                    type="number" 
                    min="1" 
                    max={shoe.stock} 
                    value={quantity}
                    onChange={(e) => setQuantity(e.target.value)}
                    /> {' '} unit
                </p>
                <p className="price">Total Price: ${quantity * shoe.price}</p>
                <button className="btn btn-primary">Add to Cart</button>
              </> :
              <>
                <p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
                <button className="btn btn-secondary">Notify Me!</button>
              </>
            }

          </div>

        </div>
      </div>  
    </Layout>
  )
}

export const query = graphql`
  query($slug: String!) {
    strapiProduct(slug: {eq: $slug}) {
      id
      title
      price
      status
      stock
      categories {
        name
        slug
      }
      company {
        name
        slug
      }
      description
      image {
        url
      }
      updatedAt
    }
  }
`

 

Trong đoạn mã trên, chúng tôi thực hiện truy vấn GraphQL để tìm nạp thông tin chi tiết của sản phẩm (giày) dựa trên giá trị slug.

Chúng tôi có thể sử dụng các chi tiết sản phẩm để xây dựng cấu trúc khi chúng tôi tìm nạp các chi tiết sản phẩm. Trong trường hợp này, cấu trúc bao gồm ảnh của sản phẩm và thông tin như danh mục, công ty, giá cả và kho. Trang này cũng bao gồm hộp số đầu vào để chỉ định số lượng giày cần thiết và tự động tính toán tổng số tiền phải trả cho một lần thanh toán.

Tất cả điều này là tuyệt vời, nhưng làm thế nào để chúng tôi lấy giá trị slug của giày và ánh xạ nó với shoe-detailsmẫu? Hãy thử và làm điều đó ngay bây giờ.

Mở gatsby-node.jstệp và thay thế nội dung bằng mã sau:

// gatsby-node.js

exports.createPages = async function ({ actions, graphql }) {
  const { data } = await graphql(`
    query {
      allStrapiProduct {
        edges {
          node {    
            slug
          }
        }
      }
    }
  `)
  data.allStrapiProduct.edges.forEach(edge => {
    const slug = edge.node.slug
    actions.createPage({
      path: slug,
      component: require.resolve(`./src/templates/shoe-details.js`),
      context: { slug: slug },
    })
  })
}

Gatsby chạy gatsby-node.jstệp tại thời điểm xây dựng. Ở đây, chúng tôi tìm nạp các slugs cho tất cả các sản phẩm, vì vậy chúng tôi có thể tích hợp các slugs và tạo các trang cho từng sản phẩm.

Phương createPagethức lấy một đối tượng làm đối số trong đó chúng tôi cung cấp chi tiết về đường dẫn được tham chiếu với slug và ánh xạ tới thành phần nào. Xin lưu ý rằng thành phần là tệp mẫu mà chúng ta đã thấy ở trên. Chúng tôi cũng truyền dữ liệu ngữ cảnh là chính slug.

Vì vậy, mỗi đường dẫn với giá trị slug bây giờ được ánh xạ tới tệp mẫu, với giá trị slug được truyền dưới dạng ngữ cảnh. Chúng tôi đã tìm hiểu cách thành phần mẫu sử dụng giá trị slug này và tìm nạp các chi tiết của sản phẩm. Tôi hy vọng tất cả các dấu chấm được kết nối tốt ngay bây giờ.

Bây giờ, hãy mở shoes.csstệp và thêm các kiểu sau vào bên dưới những kiểu hiện có. Các phong cách sau đây dành cho trang chi tiết giày.

.shoe-details {
  padding: 1rem;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.shoe-details .cover {
  display: flex;
  align-content: center;
  justify-content: center;
}

.shoe-details .cover > IMG {
  width: 30rem;
  height: 30rem;
  border-radius: 50%;
}

.shoe-details .info-heading {
  margin-bottom: 1rem;
}

.shoe-details .info-heading > a {
  color: #1af41a;
  text-decoration: underline;
}

.shoe-details .info-heading > H2 {
  font-size: 3rem;
}

.shoe-details .info-body > P {
  margin: 0;
}

.shoe-details .info-body > SPAN {
  font-size: 1.5rem;
}

.shoe-details .info-purchase {
  margin: 2rem 0 0 0;
  border: 1px solid #4a4545;
  border-radius: 5px;
  padding: 1rem;
  background-color: black;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.shoe-details .info-purchase .price {
  font-size: 1.5rem;
  font-weight: 500;
  color: #ffffff;
}

.shoe-details .info-purchase INPUT {
  border: 1px solid #ececec;
  padding: 5px;
  border-radius: 3px;
  font-size: 1rem;
}

.shoe-filtered-list H2 {
  font-size: 2rem;
  font-weight: 500;
  color: #1af41a;
  margin: 0 0 1rem 1rem;
}

@media only screen and (max-width: 900px) {
  .shoe-details {
    padding: 1rem;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
}

@media only screen and (max-width: 600px) {
  .shoe-details .cover > IMG {
    width: 20rem;
    height: 20rem;
  }
}

Bây giờ khởi động lại máy chủ cục bộ của Gatsby và truy cập lại vào ứng dụng localhost:8000. Nhấp vào bất kỳ thẻ giày nào; bạn sẽ thấy một trang thanh lịch, hiển thị với các chi tiết giày.

shoe-details.png

Được rồi, đó là tất cả những gì chúng tôi muốn xây dựng với Gatsby và Strapi: một cửa hàng giày Jamstack với một vài trang được phục vụ tĩnh. Và chúng tôi đã làm được!

Tuy nhiên, đừng lo lắng: bạn có thể đi xa hơn từ đây. Bạn có thể tạo mẫu cho các danh mục và công ty và có các trang cho từng danh mục. Bạn có thể phát triển các chức năng tìm kiếm và tạo các tùy chọn lọc cho giày theo tiêu đề, phạm vi giá, công ty và danh mục. Mã dự án là mã nguồn mở theo giấy phép MIT trên GitHub.

Như một bản tóm tắt nhanh, hãy xem video giới thiệu nhanh bên dưới. Đây là bản demo của shoesứng dụng mà chúng tôi đã xây dựng trong bài viết này, cùng với một số chức năng bổ sung được đề cập ở trên.

Liên kết: https://blog.greenTHER.info/build-your-ecommerce-store-using-gatsby-and-strapi

#ecommerce #gatsby #strapi #javascript

Cách Xây Dựng Cửa Hàng Thương Mại điện Tử Của Bạn Bằng Gatsby & Strapi

Как создать свой интернет-магазин с помощью Gatsby и Strapi

Узнайте, как создать интернет-магазин Jamstack с помощью Gatsby и Strapi. Мы создадим интернет-магазин обуви поэтапно.

Давайте начнем с вопроса: при создании веб-сайта или приложения в наши дни, что нам нужно учитывать в первую очередь?

Что ж, на этот вопрос есть множество потенциальных ответов, но speed, cost, и securityдолжны занимать видное место независимо от того, что мы строим. Будь то блог-сайт, личный веб-сайт или портал электронной коммерции, наши пользователи ожидают, что он будет быстро загружаться, недорог в обслуживании и безопасен для конечных пользователей.

К счастью, архитектура Jamstack может помочь нам во всех трех аспектах.

Jamstack позволяет нам создавать статические веб-сайты, используя готовые разметки, бессерверные API… даже данные из CMS. Эти статические сайты работают быстрее, чем альтернативные, поскольку разметка предварительно создается и безопасно обслуживается с защищенного CDN (вместо исходного сервера).

И существует целая технологическая экосистема, поддерживающая создание приложений Jamstack. В этой статье мы рассмотрим две самые известные из этих технологий: Gatsbyи Strapi.мы будем использовать их для создания приложения для электронной коммерции — интернет-магазина обуви под названием « shoes.Оригинал», верно?

Гэтсби и Страпи

Gatsby — это генератор статических сайтов на основе React, специально разработанный для создания готовых разметки и предлагающий единую облачную платформу для создания, предварительного просмотра и размещения ваших приложений. Он очень быстрый, легко интегрируется с различными источниками данных и поставляется с множеством подключаемых экосистем.

Strapi, с другой стороны, представляет собой настраиваемое приложение с открытым исходным кодом, которое помогает вам быстрее создавать API и легко управлять своим контентом. Любой внешний клиент может использовать API-интерфейсы с помощью REST или GraphQL, и вы можете легко самостоятельно разместить приложение Strapi у поставщика, такого как Heroku.

Эти две программы прекрасно сочетаются друг с другом: в то время как Gatsby обеспечивает более быстрый внешний интерфейс, Strapi устраняет необходимость в внутреннем хранилище данных и системе управления контентом (CMS).

Хорошо, теперь вы знаете, что могут предложить Gatsby и Strapi, давайте посмотрим, как они работают на практике, создав shoesприложение.

Начало работы с shoesприложением

Мы разделим shoesприложение на две основные части:

  1. datastore: для этого требуется Strapiпроект со всем содержимым и API, необходимыми для приложения.
  2. client: это зависит от Gatsbyпроекта, который использует API с помощью GraphQL для извлечения контента из Strapi и отображения его в красивых пользовательских интерфейсах.

Во-первых, мы datastoreнастроим использование Strapi. Обратите внимание, что для локального запуска приложения у вас должен быть установлен Node.js. У вас также есть возможность установить пряжу , но если у вас нет пряжи, используйте npmвместо нее .

Использование datastore_Strapi

Strapi предоставляет множество шаблонов для быстрого начала работы с приложением. Поскольку наш обувной магазин является приложением для электронной коммерции, мы будем использовать ecommerceшаблон для создания файла datastore.

Для этого просто создайте shoesпапку и откройте командную строку (или терминал) в каталоге обуви.

Теперь используйте следующую команду для создания проекта Strapi:

yarn create strapi-app datastore --template ecommerce

Обратите внимание, что мы указали имя проекта datastoreи шаблон, как ecommerceв приведенной выше команде.

Команде потребуется некоторое время, чтобы загрузить необходимые зависимости, установить их и настроить для вас. Однако, как только это будет сделано, приложение Strapi будет доступно в вашем браузере по URL-адресу [localhost:1337](http://localhost:1337).

Также важно помнить, что вам необходимо зарегистрировать свой профиль в первый раз, чтобы создать свои учетные данные. Эти же учетные данные будут использоваться для аутентификации в Strapi, поэтому, пожалуйста, найдите время, чтобы заполнить обязательные данные и зарегистрироваться.

1-strapi-initial.png

После регистрации вы попадете на страницу приветствия Strapi. Это даст вам ориентиры, необходимые для создания структуры контента, присоединения к сообществам и выполнения многих других функций.

2-админ-панель.png

Создать типы

Теперь приступим к созданию typesв Strapi. Вы можете думать об этих типах как о таблицах со схемой в реляционной базе данных.

Для нашего приложения мы хотим создать данные об обуви как Productтип. Каждый обувной продукт будет иметь свою собственную метаинформацию, такую ​​как название, цена, описание, акции, категория и компания.

Мы также будем управлять Categoryи Companyкак независимыми типами, и создавать отношения с Productтипом.

Итак, давайте начнем создавать типы один за другим. Сначала создайте следующие поля для Categoryтипа:

  • name : Поле текстового типа.
  • slug : фрагмент URL для идентификации этой категории. Это тип UID

Скриншот 14 июля 2022 г., 22:22:40.png

Точно так же вы можете создать тип компании с полями имени и ярлыка.

Скриншот 14 июля 2022 г., 21:49:27.png

А теперь мы создадим тип продукта с полями, показанными на изображении ниже.

Скриншот 04 июля 2022 г., 15:55:56.png

Большинство полей выше говорят сами за себя. Однако некоторые поля требуют пояснений.

  • image : это относится к изображению продукта и типу Media. В Strapi вы можете загружать активы (изображения, видео, файлы) в медиатеку, чтобы использовать их позже.
  • категории и компании относятся к соответствующим типам, которые мы уже создали.
  • статус : Поле указывает статус продукта.
  • stock : числовое поле содержит информацию о количестве обуви на складе.

Вставить данные

Поскольку все необходимые типы теперь созданы, мы можем приступить к созданию примеров данных в Strapi. Во-первых, давайте загрузим несколько крутых изображений обуви. Вы можете собирать их с медиа-сайта, например, unsplashи загружать элементы из Media Libraryменю.

Скриншот 04 июля 2022 г., 15:56:38.png

Затем просмотрите параметр «Диспетчер содержимого» в левой части навигации и начните создавать записи для типа категории. Вы можете создать категории, упомянутые на изображении ниже, или создать свои собственные.

Скриншот 04.07.2022, 15:57:05.png

Аналогичным образом вставьте записи для данных компании.Скриншот 04.07.2022, 15:57:22.png

Наконец, введите данные для типа продукта.

Скриншот 04.07.2022, 16.07.19.png

Токены API

На данный момент мы создали весь необходимый контент в Strapi и собираемся использовать все элементы пользовательского интерфейса с помощью API Strapi. Вы можете получить доступ к API Strapi, используя REST для GraphQL, но помните, что вам необходимо получить токен API для выполнения успешных вызовов API.

Нажмите «Настройки»> «Глобальные настройки»> «Токены API» на левой панели навигации и нажмите Create new API Tokenкнопку, чтобы создать токен полного доступа для приложения «Обувь». Пожалуйста, сохраните этот токен при себе, потому что мы будем использовать его в ближайшее время.

Скриншот 04.07.2022, 16.07.45.png

Использование client_Gatsby

Мы успешно настроили datastoreStrapi, и теперь пришло время настроить clientсторону с Gatsby.

Для этого откройте другую командную строку/терминал в корневой папке проекта и выполните следующую команду.

yarn global add gatsby-cli

Эта команда установит интерфейс командной строки Gatsby (CLI) глобально. Это помогает нам взаимодействовать со структурой Gatsby для выполнения различных задач.

Как и Strapi, Gatsby поставляется с несколькими шаблонами для создания проекта. В мире Гэтсби они называются «начальными шаблонами». Мы будем использовать начальный шаблон по умолчанию для создания проекта и назовем файл client.

Пожалуйста, выполните следующую команду, чтобы создать проект Gatsby.

npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default

Приведенная выше команда займет некоторое время и создаст для вас структуру проекта. Теперь перейдите в clientкаталог и запустите приложение локально с помощью gatsby developкоманды.

cd client
gatsby develop

Приложение Gatsby будет работать по [localhost:8000](http://localhost:8000)URL-адресу, и вы увидите такой пользовательский интерфейс при доступе к нему с помощью браузера. Это страница по умолчанию из начального шаблона, который мы использовали. Мы изменим его в ближайшее время.

Скриншот 04.07.2022, 16:28:49.png

Гэтсби и Страпи: совместная история лучше

Итак, теперь мы объединим Gatsby и Strapi, чтобы придать форму нашему приложению. Мы будем вызывать API-интерфейсы Strapi из Gatsby и получать данные об обуви во время сборки.

Экосистема подключаемых модулей Gatsby имеет подключаемый модуль источника gatsby-source-strapi, который помогает получать данные из Strapi с помощью GraphQL. Давайте установим этот плагин и еще несколько зависимостей для обработки изображений и преобразования. Пожалуйста, выполните следующую команду из терминала в clientкаталоге.

yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp

Создайте файл с именем .env.developmentв корне clientпапки со следующим содержимым.

STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337

Вот <STRAPI-API-TOKEN>токен, который вы скопировали при настройке хранилища данных Strapi. Теперь вы можете импортировать clientпроект в свой любимый редактор кода (в моем случае, например, в VS Code).

Теперь откройте gatsby-config.jsфайл и замените содержимое приведенным ниже содержимым. Это файл конфигурации, который определяет метаданные сайта и параметры плагинов.

Внимательно изучите параметры, которые мы определили для gatsby-source-strapiподключаемого модуля: мы указали URL-адрес API Strapi, токен API и имена типов коллекций, с которыми мы хотим взаимодействовать.

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  siteMetadata: {
    title: `Shoes`,
    description: `The one stop shop for your shoes and footwear needs.`,
    author: `@tapasadhikary`,
    siteUrl: `https://shoes.io/`,
  },
  plug-ins: [
    "gatsby-plugin-gatsby-cloud",
    {
      resolve: "gatsby-source-strapi",
      options: {
        apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
        accessToken: process.env.STRAPI_TOKEN,
        collectionTypes: [
          {
            singularName: "product",
          },
          {
            singularName: "company",
          },
          {
            singularName: "category",
          },
        ],
      },
    },
    "gatsby-plugin-image",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    "gatsby-transformer-remark",
  ],
}

Пожалуйста, остановите и перезапустите gatsby developфункцию и перейдите по URL-адресу http://localhost:8000/__graphql, чтобы открыть проводник Gatsby GraphQL.

Gatsby предоставляет проводник GraphQL в качестве инструмента разработчика, поэтому вы можете легко создавать запросы GraphQL. Вы должны найти все типы коллекций Strapi в крайнем левом Explorerстолбце: все они начинаются с текста allStrapi.

Итак, давайте теперь попробуем построить пример запроса для allStrapiProductколлекции. Вы можете расширить коллекцию и выбрать поля, для которых вы хотите получить данные; вы увидите, что запрос GraphQL создается автоматически на основе вашего выбора.

Теперь вы можете запустить запрос, нажав кнопку «Выполнить» в заголовке средней панели. Вы можете найти вывод в самой правой панели.

Я предлагаю вам провести некоторое время с проводником GraphQL и поиграться с запросами, чтобы привыкнуть к нему.

Скриншот 04.07.2022, 16:36:51.png

Чтобы построить запросы GraphQL, мы будем использовать их для создания компонентов пользовательского интерфейса. Gatsby основан на React, поэтому вы можете использовать всю мощь библиотеки React в Gatsby. Просто откройте index.jsфайл и замените существующее содержимое следующим кодом.

// index.js

import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"

import { useStaticQuery, graphql } from "gatsby"

import '../style/shoes.css'

const IndexPage = () => {
  const { allStrapiProduct } = useStaticQuery(graphql`
    query {
      allStrapiProduct(sort: {order: ASC, fields: title}) {
        edges {
          node {
            image {
              url
            }
            slug
            price
            title
            id
            stock
            status
          }
        }
      }
    }
  `)

  return (
    <Layout>
      <Seo title="Home" />
        <ShoeList shoes={allStrapiProduct.edges} />
    </Layout>
  )
}

export default IndexPage

 

Теперь давайте углубимся в код в index.jsфайле. Мы используем запрос GraphQL для получения всех продуктов, отсортированных по названию продукта в порядке возрастания. Gatsby предоставляет нам хук React, вызываемый useStaticQueryдля выполнения запроса GraphQL.

Затем мы передаем полученный массив продуктов (обувь) в качестве реквизита ShoeListкомпоненту. Нам нужно создать компонент, который будет перебирать shoesмассив, и начать создавать макет карты для каждой детали обуви.

Для этого создайте файл с именем ShowList.jsв componentsпапке со следующим содержимым.

// ShoeList.js

import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
  console.log(shoes);
  return (
    <div className="shoe-list">
    {shoes.map((shoe) => (
      <ShoeCard key={shoe.node.id} shoe={shoe.node} />
    ))}
    </div>
  )


}

export default ShoeList

 

Как вы заметили в приведенном выше коде, мы убираем каждую деталь обуви и передаем ее в качестве реквизита другому компоненту, ShoeCard. Итак, вам нужно создать файл с именем ShoeCard.jsв componentsпапке со следующим содержимым.

// ShoeCard.js

import * as React from "react"
import { Link } from "gatsby"

const ShoeCard = ({ shoe }) => {
  return (
    <Link
      to={`/${shoe.slug}`}
      className="shoe-card" >
        <div className="img-container">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>  
        <div className="details">
          <h2>{shoe.title} - ${shoe.price}</h2>
        </div>
    </Link>
  )
}

export default ShoeCard

 

Компонент ShoeCard отображает изображение обуви, название и цену. Позже мы будем показывать название и цену только тогда, когда пользователь наведет курсор на изображение обуви, используя стили CSS.

Также обратите внимание, что карточка обуви упакована в файл Link. Компонент Link принадлежит Gatsby и помогает нам создавать ссылки между страницами в приложении Gatsby. Компонент Link имеет атрибут, который мы используем для ссылки на целевую страницу. В приведенном выше примере значением атрибута является значение slug каждой обуви.

Мы намерены переходить на новую страницу, когда пользователь нажимает на карточку обуви; эта новая страница будет отображать более подробную информацию об обуви и вариантах покупки. Но нам нужно внести некоторые изменения, и мы сделаем это позже. Во-первых, нам нужно сосредоточиться на подготовке страницы списка обуви со всеми стилями.

Давайте немного подправим компоненты Layout и Header. Сначала замените содержимое layout.jsфайла следующим содержимым. Он очень похож на существующий файл layout.js, поставляемый с шаблоном, но мы внесли некоторые незначительные изменения стиля.

// layout.js

import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"

import Header from "./header"
import "./layout.css"

const Layout = ({ children }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)

  return (
    <>
      <Header siteTitle={data.site.siteMetadata?.title || `Title`} />
      <div className="container">
        <main className="content">{children}</main>
        <footer>
          © {new Date().getFullYear()} &middot; Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
        </footer>
      </div>
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

 

Вот содержимое Header.jsфайла, который нужно заменить в существующем файле.

// Header.js

import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"

const Header = ({ siteTitle }) => (
  <header>
    <Link to="/" className="logo">
    👠 {siteTitle}
    </Link>
  </header>
)

Header.propTypes = {
  siteTitle: PropTypes.string,
}

Header.defaultProps = {
  siteTitle: ``,
}

export default Header

Теперь давайте создадим styleпапку в srcкаталоге. Для этого создайте в папке shoes.cssфайл styleсо следующим содержимым.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");

*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  scroll-behavior: smooth;
}
html {
  overflow: auto;
}

body {
  height: 100vh;
  background-color: rgb(3, 28, 34);
  color: #ffffff;
  font-family: "Poppins", sans-serif;
}

a {
  text-decoration: none;
  color: #ffffff;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #282d2e;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  margin: 0 0 0.5rem 0;
}

header .logo {
  font-size: 2rem;
  font-weight: 500;
  color: #ffffff;
  padding: 0.5rem;
}

footer {
  width: 100%;
  padding: 0.3rem;
  background-color: #282d2e;
  text-align: center;
}

footer > a {
  color: #1af41a;
  text-decoration: underline;
}

.btn {
  padding: 10px;
  cursor: pointer;
  font-size: 18px;
  border: none;
  border-radius: 10px;
}

.btn.btn-primary {
  background-color: #40ee10;
  color: #000000;
}

.btn.btn-primary:hover {
  background-color: #70e007;
  color: #000000;
}

.btn.btn-secondary {
  background-color: #ffffff;
  color: #282d2e;
}

.btn.btn-secondary:hover {
  background-color: #282d2e;
  color: #ffffff;
}

.container {
  height: calc(100vh - 73px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content {
  flex-grow: 1;
  overflow: auto;
}

.shoe-list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.shoe-card {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  width: 15rem;
  height: 15rem;
  margin: 1.2rem;
}

.shoe-card .img-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  transition: all 0.5s ease-in-out;
}

.shoe-card .img-container > IMG {
  width: 15rem;
  height: 15rem;
  object-fit: cover;
  resize: both;
  border-radius: 10px;
}

.shoe-card:hover .img-container {
  transform: translate(-1rem, -1rem);
}

.shoe-card:hover .details {
  transform: translate(1rem, 1rem);
}

.shoe-card .details {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 0.5rem;
  display: flex;
  background-color: #fff;
  z-index: 1;
  align-items: flex-end;
  transition: 0.5s ease-in-out;
  line-height: 1rem;
  border-radius: 10px;
}

.shoe-card .details h2 {
  display: block;
  font-size: 1rem;
  color: #000000;
  font-weight: 500;
}

Вот и все!

Теперь запустите приложение локально, используя URL-адрес [http://localhost:8000](http://localhost:8000), и вы увидите список изображений обуви на странице. Наведите указатель мыши на изображения обуви, и анимация покажет название обуви и цену.

список обуви.png

Замечательно. Итак, теперь попробуйте нажать на любую из карточек с обувью.

Ой! вы получаете страницу, как показано ниже, и она выглядит сломанной. Он попытался перейти на страницу, идентифицированную значением слага обуви, но безуспешно.

Но не беспокойтесь, мы можем решить проблему.

Скриншот 11 июля 2022 г., 21:44:03.png

Gatsby может создавать страницы во время сборки, используя шаблоны. Они используют ту же структуру пользовательского интерфейса, которую вы хотите использовать для другого набора данных.

Например, в нашем shoesприложении мы хотим показать детали каждой обуви. Структура страницы сведений будет такой же, но данные обуви будут меняться в зависимости от того, на какое изображение обуви мы нажимаем.

Итак, мы можем создать шаблон shoe-details.jsпод названием src/templatesпапки со следующим содержимым.

// shoe-details.js

import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"

export default function ShoeDetails({ data }) {
  const shoe = data.strapiProduct
  const [quantity, setQuantity] = useState(1)
  return (
    <Layout>
      <div className="shoe-details">
        <div className="cover">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>
        <div className="info">
          <div className="info-heading">
            <h2>{shoe.title}</h2> 
            <Link to={`/category/${shoe.categories[0].slug}`}>
              <span>{shoe.categories[0].name}</span>
            </Link> { ' '}
            from {' '}
            <Link to={`/company/${shoe.company.slug}`}>
              {shoe.company.name}
            </Link>
          </div>

          <div className="info-body">
            <p>{shoe.description}</p>
            <span>${shoe.price} per unit</span> { ' - '}
            <>
              {
                shoe.stock > 0 ?
                  <span>{shoe.stock} In Stock</span> :
                  <span>Out of Stock</span>
              }
            </>
          </div>

          <div className="info-purchase">
            {
              shoe.stock > 0 ?
              <>
                <p>
                  I want to purchase {' '}
                  <input 
                    type="number" 
                    min="1" 
                    max={shoe.stock} 
                    value={quantity}
                    onChange={(e) => setQuantity(e.target.value)}
                    /> {' '} unit
                </p>
                <p className="price">Total Price: ${quantity * shoe.price}</p>
                <button className="btn btn-primary">Add to Cart</button>
              </> :
              <>
                <p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
                <button className="btn btn-secondary">Notify Me!</button>
              </>
            }

          </div>

        </div>
      </div>  
    </Layout>
  )
}

export const query = graphql`
  query($slug: String!) {
    strapiProduct(slug: {eq: $slug}) {
      id
      title
      price
      status
      stock
      categories {
        name
        slug
      }
      company {
        name
        slug
      }
      description
      image {
        url
      }
      updatedAt
    }
  }
`

 

В приведенном выше коде мы выполняем запрос GraphQL для получения сведений о продукте (обуви) на основе значения слага.

Мы можем использовать сведения о продукте для построения структуры при получении сведений о продукте. В этом случае структура включает в себя фото товара и такую ​​информацию, как категория, компания, цена и наличие на складе. На странице также есть поле ввода числа, чтобы указать необходимое количество обуви и автоматически рассчитать общую сумму для оплаты при оформлении заказа.

Все это здорово, но как нам получить значение slug обуви и сопоставить его с shoe-detailsшаблоном? Давайте попробуем сделать это сейчас.

Откройте gatsby-node.jsфайл и замените содержимое следующим кодом:

// gatsby-node.js

exports.createPages = async function ({ actions, graphql }) {
  const { data } = await graphql(`
    query {
      allStrapiProduct {
        edges {
          node {    
            slug
          }
        }
      }
    }
  `)
  data.allStrapiProduct.edges.forEach(edge => {
    const slug = edge.node.slug
    actions.createPage({
      path: slug,
      component: require.resolve(`./src/templates/shoe-details.js`),
      context: { slug: slug },
    })
  })
}

Gatsby запускает gatsby-node.jsфайл во время сборки. Здесь мы получаем слаги для всех продуктов, чтобы затем интегрировать слаги и создавать страницы для каждого из них.

Метод createPageпринимает объект в качестве аргумента, где мы предоставляем детали пути, на который ссылается слаг, и сопоставляем с каким компонентом. Обратите внимание, что компонент — это файл шаблона, который мы видели выше. Мы также передаем контекстные данные, которые являются самим слагом.

Таким образом, каждый путь со значением slug теперь сопоставляется с файлом шаблона, а значение slug передается в качестве контекста. Мы уже узнали, как компонент шаблона использует это значение slug и извлекает сведения о продукте. Надеюсь, теперь все точки хорошо связаны.

Теперь откройте shoes.cssфайл и добавьте следующие стили ниже существующих. Следующие стили предназначены для страницы сведений об обуви.

.shoe-details {
  padding: 1rem;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.shoe-details .cover {
  display: flex;
  align-content: center;
  justify-content: center;
}

.shoe-details .cover > IMG {
  width: 30rem;
  height: 30rem;
  border-radius: 50%;
}

.shoe-details .info-heading {
  margin-bottom: 1rem;
}

.shoe-details .info-heading > a {
  color: #1af41a;
  text-decoration: underline;
}

.shoe-details .info-heading > H2 {
  font-size: 3rem;
}

.shoe-details .info-body > P {
  margin: 0;
}

.shoe-details .info-body > SPAN {
  font-size: 1.5rem;
}

.shoe-details .info-purchase {
  margin: 2rem 0 0 0;
  border: 1px solid #4a4545;
  border-radius: 5px;
  padding: 1rem;
  background-color: black;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.shoe-details .info-purchase .price {
  font-size: 1.5rem;
  font-weight: 500;
  color: #ffffff;
}

.shoe-details .info-purchase INPUT {
  border: 1px solid #ececec;
  padding: 5px;
  border-radius: 3px;
  font-size: 1rem;
}

.shoe-filtered-list H2 {
  font-size: 2rem;
  font-weight: 500;
  color: #1af41a;
  margin: 0 0 1rem 1rem;
}

@media only screen and (max-width: 900px) {
  .shoe-details {
    padding: 1rem;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
}

@media only screen and (max-width: 600px) {
  .shoe-details .cover > IMG {
    width: 20rem;
    height: 20rem;
  }
}

Теперь перезапустите локальный сервер Гэтсби и снова войдите в приложение на localhost:8000. Нажмите на любую из карт обуви; вы должны увидеть элегантную страницу с деталями обуви.

Детали обуви.png

Хорошо, это все, что мы хотели создать с Gatsby и Strapi: обувной магазин Jamstack с парой страниц, обслуживаемых статически. И мы сделали это!

Однако не волнуйтесь: отсюда вы можете пойти гораздо дальше. Вы можете создавать шаблоны для категорий и компаний и иметь страницы для каждой из них. Вы можете разработать функции поиска и создать параметры фильтрации обуви по названию, ценовому диапазону, компании и категории. Код проекта находится в открытом доступе под лицензией MIT на GitHub.

В качестве краткого обзора посмотрите краткое демонстрационное видео ниже. Это демонстрация shoesприложения, которое мы создали в этой статье, вместе с несколькими дополнительными функциями, упомянутыми выше.

Ссылка: https://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi

#ecommerce #gatsby #strapi #javascript

Как создать свой интернет-магазин с помощью Gatsby и Strapi
田辺  亮介

田辺 亮介

1659428880

如何使用 Gatsby 和 Strapi 構建您的電子商務商店

了解如何使用 Gatsby 和 Strapi 創建 Jamstack 電子商務商店。我們將逐步建立一個在線鞋店。

讓我們從一個問題開始:在這個時代構建網站或應用程序時,我們需要考慮的主要事項是什麼?

好吧,這個問題有很多潛在的答案,但是speed,無論我們正在構建什麼,都應該突出顯示costsecurity無論是博客網站、個人網站還是電子商務門戶網站,我們的用戶都希望它能夠快速加載、維護成本低廉並且對最終用戶而言是安全的。

值得慶幸的是,Jamstack 架構可以在所有三個方面為我們提供幫助。

Jamstack 允許我們使用預構建的標記、無服務器 API……甚至來自 CMS 的數據來構建靜態網站。這些靜態站點比其他站點更快,因為標記是預先構建的,並從安全的 CDN(而不是原始服務器)安全地提供服務。

還有一個完整的技術生態系統支持創建 Jamstack 應用程序。在本文中,我們將討論其中最知名的兩項技術:Gatsby我們將使用它們來構建一個電子商務應用程序——一個名為OriginalStrapi.的在線鞋店,對吧?shoes.

蓋茨比和斯特拉皮

Gatsby是一個基於 React 的靜態站點生成器,專門設計用於創建預構建標記,並為構建、預覽和託管您的應用程序提供統一的雲平台。它超級快速,易於與各種數據源集成,並帶有大量的插件生態系統。

另一方面,Strapi 是一個開源、高度可定制的應用程序,可幫助您更快地構建 API 並輕鬆管理您的內容。任何前端客戶端都可以使用 REST 或 GraphQL 使用 API,並且您可以在 Heroku 等提供程序上輕鬆自託管 Strapi 應用程序。

這兩個程序完美契合:雖然 Gatsby 提供了更快的前端,但 Strapi解決了對後端數據存儲和內容管理系統 (CMS) 的需求。

好的,現在您知道 Gatsby 和 Strapi 可以提供什麼,讓我們通過構建shoes應用程序來看看它們在實踐中是如何工作的。

開始使用shoes應用程序

我們將shoes應用程序分為兩個主要部分:

  1. datastore:這需要Strapi項目,以及應用程序所需的所有內容和 API。
  2. client:這依賴於Gatsby項目,該項目在 GraphQL 的幫助下使用 API 從 Strapi 獲取內容並將其呈現在漂亮的用戶界面中。

首先,我們將設置datastore使用 Strapi。請注意,您必須安裝Node.js才能在本地運行應用程序。您還可以選擇安裝yarn,但如果您沒有 yarn,請npm改用。

使用_datastoreStrapi

Strapi 提供了一堆模板來快速開始使用該應用程序。由於我們的鞋店是一個電子商務應用程序,我們將使用ecommerce模板來創建datastore.

為此,只需創建一個shoes文件夾並在 shoes 目錄上打開命令提示符(或終端)。

現在,使用以下命令創建一個 Strapi 項目:

yarn create strapi-app datastore --template ecommerce

請注意,我們在上述命令中提供了項目名稱datastore和模板。ecommerce

該命令將需要一段時間來下載所需的依賴項、安裝它們並為您設置它們。但是,一旦完成,Strapi 應用程序將可以在您的瀏覽器上使用 URL 訪問[localhost:1337](http://localhost:1337)

同樣重要的是要記住,您需要首次註冊您的個人資料以創建您的憑據。這些相同的憑據將用於在 Strapi 中進行身份驗證,因此請花時間填寫強制性詳細信息並進行註冊。

1-strapi-initial.png

註冊後,您將登陸 Strapi 的歡迎頁面。這將為您提供創建內容結構、加入社區和完成更多功能所需的指導。

2-管理面板.png

創建類型

現在我們將開始types在 Strapi 中創建。您可以將這些類型視為關係數據庫中具有架構的表。

對於我們的應用程序,我們希望將鞋子數據創建為一種Product類型。每個鞋類產品都有自己的元信息,如名稱、價格、描述、庫存、類別和公司。

我們還將管理CategoryCompany作為獨立類型,並創建與Product類型的關係。

所以,讓我們開始一一創建類型。首先,為該Category類型創建以下字段:

  • name:文本類型字段。
  • slug:用於標識此類別的 URL 片段。它的類型為 UID

截圖 2022-07-14 在 9.22.40 PM.png

同樣,您可以使用名稱和 slug 字段創建公司類型。

截圖 2022-07-14 在 9.49.27 PM.png

現在我們將創建 Product 類型,其字段如下圖所示。

屏幕截圖 2022-07-04 下午 3.55.56.png

上面的大部分字段都是不言自明的。但是,有幾個領域需要解釋。

  • image:這是指產品的圖像,類型為Media。在 Strapi 中,您可以將資產(圖像、視頻、文件)上傳到媒體庫以供以後使用。
  • 類別公司與我們已經創建的相應類型相關。
  • status:一個字段表示產品的狀態。
  • stock:一個數字字段保存庫存中鞋子數量的記錄。

插入數據

由於現在創建了所有必需的類型,我們可以開始在 Strapi 中創建示例數據。首先,讓我們上傳一些很酷的鞋子圖片。您可以從媒體網站上收集它們,例如從菜單中unsplash上傳項目。Media Library

屏幕截圖 2022-07-04 下午 3.56.38.png

接下來,從左側導航瀏覽 Content Manager 選項並開始為 Category 類型創建條目。您可以創建下圖中提到的類別,也可以隨意創建自己的類別。

屏幕截圖 2022-07-04 下午 3.57.05.png

同樣,為公司數據插入條目。屏幕截圖 2022-07-04 下午 3.57.22.png

最後,輸入產品類型的數據。

屏幕截圖 2022-07-04 下午 4.07.19.png

API 令牌

到目前為止,我們已經在 Strapi 中創建了所有必需的內容,並且即將通過 Strapi API 使用 UI 中的所有元素。您可以使用 REST 到 GraphQL 訪問 Strapi API,但請記住,您需要獲取 API 令牌才能成功調用 API。

單擊左側導航欄中的設置 > 全局設置 > API Tokens,然後單擊Create new API Token按鈕為鞋子應用程序創建完全訪問令牌。請妥善保管此令牌,因為我們很快就會使用它。

屏幕截圖 2022-07-04 下午 4.07.45.png

使用_clientGatsby

我們已經成功地設置了datastoreStrapi,所以現在是時候設置client側邊了Gatsby

為此,請在項目的根文件夾中打開另一個命令提示符/終端並執行以下命令。

yarn global add gatsby-cli

此命令將全局安裝 Gatsby 命令行界面 (CLI)。這有助於我們與 Gatsby 框架交互以執行不同的任務。

就像 Strapi 一樣,Gatsby 提供了幾個模板來創建項目。在 Gatsby 世界中,這些被稱為“入門模板”。我們將使用默認的啟動模板來創建項目並將client.

請執行以下命令創建 Gatsby 項目。

npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default

上面的命令將花費一些時間並為您創建項目結構。現在切換到目錄並使用命令client在本地啟動應用程序。gatsby develop

cd client
gatsby develop

Gatsby 應用程序將在[localhost:8000](http://localhost:8000)URL 上運行,當您使用瀏覽器訪問它時,您將看到這樣的 UI。這是我們使用的起始模板的默認頁面。我們很快就會改變它。

屏幕截圖 2022-07-04 下午 4.28.49.png

蓋茨比和斯特拉皮:一個更好的故事

所以,現在我們將把 Gatsby 和 Strapi 結​​合在一起,來塑造我們的應用程序。我們將從 Gatsby 調用 Strapi API 並在構建時獲取鞋子數據。

Gatsby 插件生態系統有一個名為的源插件,gatsby-source-strapi它有助於使用 GraphQL 從 Strapi 獲取數據。讓我們安裝該插件和一些用於處理圖像和轉換的依賴項。請從目錄中的終端執行以下命令client

yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp

.env.development在文件夾的根目錄創建一個名為的client文件,其內容如下。

STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337

<STRAPI-API-TOKEN>是您在設置 Strapi 數據存儲時復制的令牌。你現在可以client在你最喜歡的代碼編輯器中導入項目(比如我的 VS Code)。

現在,打開gatsby-config.js文件並將內容替換為以下內容。這是一個定義站點元數據和插件選項的配置文件。

仔細看看我們為gatsby-source-strapi插件定義的選項:我們已經指定了 Strapi API URL、API 令牌和我們想要與之交互的集合類型的名稱。

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  siteMetadata: {
    title: `Shoes`,
    description: `The one stop shop for your shoes and footwear needs.`,
    author: `@tapasadhikary`,
    siteUrl: `https://shoes.io/`,
  },
  plug-ins: [
    "gatsby-plugin-gatsby-cloud",
    {
      resolve: "gatsby-source-strapi",
      options: {
        apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
        accessToken: process.env.STRAPI_TOKEN,
        collectionTypes: [
          {
            singularName: "product",
          },
          {
            singularName: "company",
          },
          {
            singularName: "category",
          },
        ],
      },
    },
    "gatsby-plugin-image",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    "gatsby-transformer-remark",
  ],
}

請停止並重新啟動該gatsby develop功能並訪問 URLhttp://localhost:8000/__graphql以打開 Gatsby 的 GraphQL 瀏覽器。

Gatsby 提供 GraphQL explorer 作為開發者工具,因此您可以輕鬆構建 GraphQL 查詢。您應該從最左側的Explorer列中找到所有 Strapi 集合類型:它們都以 text 開頭allStrapi

好的,現在讓我們嘗試為allStrapiProduct集合構建一個示例查詢。您可以展開集合併選擇要獲取數據的字段;您將看到根據您的選擇自動創建一個 GraphQL 查詢。

現在,您可以通過點擊中間面板標題中的“運行”按鈕來運行查詢。您可以在最右側的面板中找到輸出。

我建議您花一些時間使用 GraphQL 資源管理器並嘗試使用查詢來習慣它。

屏幕截圖 2022-07-04 下午 4.36.51.png

為了構建 GraphQL 查詢,我們將使用它們來創建 UI 組件。Gatsby 是基於 React 的,因此您可以在 Gatsby 中使用 React 庫的全部功能。只需打開index.js文件並將現有內容替換為以下代碼即可。

// index.js

import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"

import { useStaticQuery, graphql } from "gatsby"

import '../style/shoes.css'

const IndexPage = () => {
  const { allStrapiProduct } = useStaticQuery(graphql`
    query {
      allStrapiProduct(sort: {order: ASC, fields: title}) {
        edges {
          node {
            image {
              url
            }
            slug
            price
            title
            id
            stock
            status
          }
        }
      }
    }
  `)

  return (
    <Layout>
      <Seo title="Home" />
        <ShoeList shoes={allStrapiProduct.edges} />
    </Layout>
  )
}

export default IndexPage

 

現在讓我們深入研究文件中的代碼index.js。我們使用 GraphQL 查詢來獲取按產品標題升序排序的所有產品。Gatsby 為我們提供了一個調用useStaticQuery來執行 GraphQL 查詢的 React 鉤子。

接下來,我們將獲取的產品數組(鞋子)作為道具傳遞給ShoeList組件。我們需要創建將遍歷shoes數組的組件,並開始為每個鞋子細節創建卡片佈局。

為此,請在該文件夾ShowList.js下創建一個名為的components文件,其內容如下。

// ShoeList.js

import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
  console.log(shoes);
  return (
    <div className="shoe-list">
    {shoes.map((shoe) => (
      <ShoeCard key={shoe.node.id} shoe={shoe.node} />
    ))}
    </div>
  )


}

export default ShoeList

 

正如您在上面的代碼中註意到的那樣,我們取出每個鞋子的細節並將它們作為道具傳遞給另一個組件 ShoeCard。所以需要在文件夾下創建一個名為ShoeCard.jscomponents文件,內容如下。

// ShoeCard.js

import * as React from "react"
import { Link } from "gatsby"

const ShoeCard = ({ shoe }) => {
  return (
    <Link
      to={`/${shoe.slug}`}
      className="shoe-card" >
        <div className="img-container">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>  
        <div className="details">
          <h2>{shoe.title} - ${shoe.price}</h2>
        </div>
    </Link>
  )
}

export default ShoeCard

 

ShoeCard 組件呈現鞋子圖像、標題和價格。稍後我們將僅在用戶使用 CSS 樣式將鼠標懸停在鞋子圖像上時顯示標題和價格。

另外,請注意鞋牌是用Link. Link 組件來自 Gatsby,它幫助我們在 Gatsby 應用程序中的頁面之間進行鏈接。Link 組件具有我們用來鏈接到目標頁面的屬性。在上面的例子中,屬性值是每隻鞋子的 slug 值。

我們打算在用戶點擊鞋卡時轉到新頁面;這個新頁面將顯示有關鞋子和購買選項的更多詳細信息。但是我們需要做一些改變,我們稍後會做。首先,我們需要專注於準備所有樣式的鞋子列表頁面。

讓我們稍微調整一下 Layout 和 Header 組件。首先,將layout.js文件內容替換為如下內容。它與模板附帶的現有 layout.js 文件非常相似,但我們進行了一些小的樣式調整。

// layout.js

import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"

import Header from "./header"
import "./layout.css"

const Layout = ({ children }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)

  return (
    <>
      <Header siteTitle={data.site.siteMetadata?.title || `Title`} />
      <div className="container">
        <main className="content">{children}</main>
        <footer>
          © {new Date().getFullYear()} &middot; Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
        </footer>
      </div>
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

 

這是Header.js您需要在現有文件中替換的文件的內容。

// Header.js

import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"

const Header = ({ siteTitle }) => (
  <header>
    <Link to="/" className="logo">
    👠 {siteTitle}
    </Link>
  </header>
)

Header.propTypes = {
  siteTitle: PropTypes.string,
}

Header.defaultProps = {
  siteTitle: ``,
}

export default Header

現在,讓我們在目錄下創建一個style文件夾src。為此,請shoes.css在文件夾下創建一個style包含以下內容的文件。

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");

*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  scroll-behavior: smooth;
}
html {
  overflow: auto;
}

body {
  height: 100vh;
  background-color: rgb(3, 28, 34);
  color: #ffffff;
  font-family: "Poppins", sans-serif;
}

a {
  text-decoration: none;
  color: #ffffff;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #282d2e;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  margin: 0 0 0.5rem 0;
}

header .logo {
  font-size: 2rem;
  font-weight: 500;
  color: #ffffff;
  padding: 0.5rem;
}

footer {
  width: 100%;
  padding: 0.3rem;
  background-color: #282d2e;
  text-align: center;
}

footer > a {
  color: #1af41a;
  text-decoration: underline;
}

.btn {
  padding: 10px;
  cursor: pointer;
  font-size: 18px;
  border: none;
  border-radius: 10px;
}

.btn.btn-primary {
  background-color: #40ee10;
  color: #000000;
}

.btn.btn-primary:hover {
  background-color: #70e007;
  color: #000000;
}

.btn.btn-secondary {
  background-color: #ffffff;
  color: #282d2e;
}

.btn.btn-secondary:hover {
  background-color: #282d2e;
  color: #ffffff;
}

.container {
  height: calc(100vh - 73px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content {
  flex-grow: 1;
  overflow: auto;
}

.shoe-list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.shoe-card {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  width: 15rem;
  height: 15rem;
  margin: 1.2rem;
}

.shoe-card .img-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  transition: all 0.5s ease-in-out;
}

.shoe-card .img-container > IMG {
  width: 15rem;
  height: 15rem;
  object-fit: cover;
  resize: both;
  border-radius: 10px;
}

.shoe-card:hover .img-container {
  transform: translate(-1rem, -1rem);
}

.shoe-card:hover .details {
  transform: translate(1rem, 1rem);
}

.shoe-card .details {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 0.5rem;
  display: flex;
  background-color: #fff;
  z-index: 1;
  align-items: flex-end;
  transition: 0.5s ease-in-out;
  line-height: 1rem;
  border-radius: 10px;
}

.shoe-card .details h2 {
  display: block;
  font-size: 1rem;
  color: #000000;
  font-weight: 500;
}

而且……就是這樣!

現在使用 URL 在本地運行應用程序[http://localhost:8000](http://localhost:8000),您將在頁面上看到鞋子圖像列表。將鼠標移到鞋子圖像上,動畫將顯示鞋子名稱和價格。

鞋子清單.png

那太棒了。所以現在,試著點擊任何一張鞋牌。

哎喲! 你得到一個像下面這樣的頁面,它看起來壞了。它試圖導航到由鞋子的 slug 值標識的頁面,但沒有成功。

不過不用擔心,我們可以解決問題。

截圖 2022-07-11 在 9.44.03 PM.png

Gatsby 可以在構建時使用模板創建頁面。它們利用您想要用於不同數據集的相同 UI 結構。

例如,在我們的shoes應用程序中,我們想要顯示每雙鞋的詳細信息。詳細信息頁面結構將相同,但鞋子數據會根據我們點擊的鞋子圖片而變化。

shoe-details.js因此,我們可以在該src/templates文件夾下創建一個名為的模板,其內容如下。

// shoe-details.js

import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"

export default function ShoeDetails({ data }) {
  const shoe = data.strapiProduct
  const [quantity, setQuantity] = useState(1)
  return (
    <Layout>
      <div className="shoe-details">
        <div className="cover">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>
        <div className="info">
          <div className="info-heading">
            <h2>{shoe.title}</h2> 
            <Link to={`/category/${shoe.categories[0].slug}`}>
              <span>{shoe.categories[0].name}</span>
            </Link> { ' '}
            from {' '}
            <Link to={`/company/${shoe.company.slug}`}>
              {shoe.company.name}
            </Link>
          </div>

          <div className="info-body">
            <p>{shoe.description}</p>
            <span>${shoe.price} per unit</span> { ' - '}
            <>
              {
                shoe.stock > 0 ?
                  <span>{shoe.stock} In Stock</span> :
                  <span>Out of Stock</span>
              }
            </>
          </div>

          <div className="info-purchase">
            {
              shoe.stock > 0 ?
              <>
                <p>
                  I want to purchase {' '}
                  <input 
                    type="number" 
                    min="1" 
                    max={shoe.stock} 
                    value={quantity}
                    onChange={(e) => setQuantity(e.target.value)}
                    /> {' '} unit
                </p>
                <p className="price">Total Price: ${quantity * shoe.price}</p>
                <button className="btn btn-primary">Add to Cart</button>
              </> :
              <>
                <p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
                <button className="btn btn-secondary">Notify Me!</button>
              </>
            }

          </div>

        </div>
      </div>  
    </Layout>
  )
}

export const query = graphql`
  query($slug: String!) {
    strapiProduct(slug: {eq: $slug}) {
      id
      title
      price
      status
      stock
      categories {
        name
        slug
      }
      company {
        name
        slug
      }
      description
      image {
        url
      }
      updatedAt
    }
  }
`

 

在上面的代碼中,我們執行 GraphQL 查詢以根據 slug 值獲取產品(鞋)的詳細信息。

當我們獲取產品詳細信息時,我們可以使用產品詳細信息來構建結構。在這種情況下,結構包括產品照片和類別、公司、價格和庫存等信息。該頁面還包括輸入數字框,以指定所需鞋子的數量,並自動計算結賬時支付的總金額。

這一切都很棒,但是我們如何獲得鞋子的 slug 值並與shoe-details模板映射呢?讓我們現在嘗試這樣做。

打開gatsby-node.js文件並將內容替換為以下代碼:

// gatsby-node.js

exports.createPages = async function ({ actions, graphql }) {
  const { data } = await graphql(`
    query {
      allStrapiProduct {
        edges {
          node {    
            slug
          }
        }
      }
    }
  `)
  data.allStrapiProduct.edges.forEach(edge => {
    const slug = edge.node.slug
    actions.createPage({
      path: slug,
      component: require.resolve(`./src/templates/shoe-details.js`),
      context: { slug: slug },
    })
  })
}

Gatsbygatsby-node.js在構建時運行該文件。在這裡,我們獲取所有產品的 slug,然後我們可以集成 slug 並為每個產品創建頁面。

createPage方法將對像作為參數,我們在其中提供使用 slug 引用的路徑的詳細信息並映射到哪個組件。請注意,該組件是我們在上面看到的模板文件。我們還傳遞了 slug 本身的上下文數據。

因此,每個帶有 slug 值的路徑現在都映射到模板文件,並將 slug 值作為上下文傳遞。我們已經了解了模板組件如何使用這個 slug 值並獲取產品的詳細信息。我希望現在所有的點都連接得很好。

現在打開shoes.css文件並在現有樣式下方添加以下樣式。以下款式為鞋款詳情頁。

.shoe-details {
  padding: 1rem;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.shoe-details .cover {
  display: flex;
  align-content: center;
  justify-content: center;
}

.shoe-details .cover > IMG {
  width: 30rem;
  height: 30rem;
  border-radius: 50%;
}

.shoe-details .info-heading {
  margin-bottom: 1rem;
}

.shoe-details .info-heading > a {
  color: #1af41a;
  text-decoration: underline;
}

.shoe-details .info-heading > H2 {
  font-size: 3rem;
}

.shoe-details .info-body > P {
  margin: 0;
}

.shoe-details .info-body > SPAN {
  font-size: 1.5rem;
}

.shoe-details .info-purchase {
  margin: 2rem 0 0 0;
  border: 1px solid #4a4545;
  border-radius: 5px;
  padding: 1rem;
  background-color: black;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.shoe-details .info-purchase .price {
  font-size: 1.5rem;
  font-weight: 500;
  color: #ffffff;
}

.shoe-details .info-purchase INPUT {
  border: 1px solid #ececec;
  padding: 5px;
  border-radius: 3px;
  font-size: 1rem;
}

.shoe-filtered-list H2 {
  font-size: 2rem;
  font-weight: 500;
  color: #1af41a;
  margin: 0 0 1rem 1rem;
}

@media only screen and (max-width: 900px) {
  .shoe-details {
    padding: 1rem;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
}

@media only screen and (max-width: 600px) {
  .shoe-details .cover > IMG {
    width: 20rem;
    height: 20rem;
  }
}

現在重新啟動 Gatsby 的本地服務器並再次訪問應用程序localhost:8000。點擊任意一張鞋牌;你應該會看到一個優雅的頁面,呈現出鞋子的細節。

鞋子細節.png

好的,這就是我們想要用 Gatsby 和 Strapi 構建的全部內容:一個有幾個靜態頁面的 Jamstack 鞋店。我們做到了!

但是,不要擔心:您可以從這裡走得更遠。您可以為類別和公司創建模板,並為每個類別創建頁面。您可以開發搜索功能並按標題、價格範圍、公司和類別為鞋子創建過濾選項。該項目代碼是在 GitHub 上的 MIT 許可下開源的。

作為快速回顧,請查看下面的快速演示視頻。shoes這是我們在本文中構建的應用程序的演示,以及上面提到的一些額外功能。

鏈接:https ://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi

#ecommerce #gatsby #strapi #javascript

如何使用 Gatsby 和 Strapi 構建您的電子商務商店
Hans  Marvin

Hans Marvin

1659421620

How to Build Your Ecommerce Store using Gatsby and Strapi

Learn how to create a Jamstack ecommerce store using Gatsby and Strapi. We will build an online shoe store with a step-by-step approach.

Let’s start with a question: When building a website or app in this day and age, what are the primary things we need to consider?

Well there are loads of potential answers to this question, but speed, cost, and security should feature prominently no matter what we’re building. Whether it’s a blogging site, personal website, or e-commerce portal, our users will expect it to be fast to load, inexpensive to maintain and secure for the end-users.

See more at: https://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi

#ecommerce #gatsby #strapi #javascript

How to Build Your Ecommerce Store using Gatsby and Strapi
Thierry  Perret

Thierry Perret

1659414317

Comment Créer Votre Boutique En Ligne Avec Gatsby Et Strapi

Apprenez à créer une boutique de commerce électronique Jamstack en utilisant Gatsby et Strapi. Nous allons construire un magasin de chaussures en ligne avec une approche étape par étape.

Commençons par une question : lors de la création d'un site Web ou d'une application de nos jours, quels sont les principaux éléments à prendre en compte ?

Eh bien, il existe de nombreuses réponses potentielles à cette question, mais speed, cost, et securitydevraient figurer en bonne place, peu importe ce que nous construisons. Qu'il s'agisse d'un site de blogs, d'un site Web personnel ou d'un portail de commerce électronique, nos utilisateurs s'attendent à ce qu'il soit rapide à charger, peu coûteux à entretenir et sécurisé pour les utilisateurs finaux.

Heureusement, l' architecture Jamstack peut nous aider sur les trois plans.

Jamstack nous permet de créer des sites Web statiques à l'aide de balisages prédéfinis, d'API sans serveur… même de données du CMS. Ces sites statiques sont plus rapides que l'alternative, car les balisages sont prédéfinis et servis en toute sécurité à partir d'un CDN sécurisé (au lieu d'un serveur d'origine).

Et il existe tout un écosystème technologique qui prend en charge la création d'applications Jamstack. Dans cet article, nous aborderons deux de ces technologies les plus connues : Gatsbyet Strapi.Nous les utiliserons pour créer une application de commerce électronique - un magasin de chaussures en ligne appelé, eh bien, shoes.Original, n'est-ce pas ?

Gatsby et Strapi

Gatsby est un générateur de site statique basé sur React spécialement conçu pour créer des balisages prédéfinis et offre une plate-forme cloud unifiée pour créer, prévisualiser et héberger vos applications. Il est super rapide, facile à intégrer à diverses sources de données et il est livré avec une pléthore d'écosystèmes de plug-ins.

Strapi, d'autre part, est une application open source hautement personnalisable qui vous aide à créer des API plus rapidement et à gérer facilement votre contenu. Tout client frontal peut consommer les API à l'aide de REST ou de GraphQL, et vous pouvez auto-héberger facilement une application Strapi sur un fournisseur comme Heroku.

Les deux programmes s'accordent parfaitement : tandis que Gatsby fournit un front-end plus rapide, Strapi résout le besoin d'un datastore back-end et d'un système de gestion de contenu (CMS).

Ok, maintenant vous savez ce que Gatsby et Strapi peuvent offrir, voyons comment ils fonctionnent en pratique en créant l' shoesapplication.

Premiers pas avec l' shoesapplication

Nous allons diviser l' shoesapplication en deux parties principales :

  1. datastore: Cela nécessite le Strapiprojet, avec tout le contenu et les API nécessaires à l'application.
  2. client: Cela repose sur le Gatsbyprojet, qui utilise des API, avec l'aide de GraphQL, pour récupérer le contenu de Strapi et le restituer dans de belles interfaces utilisateur.

Tout d'abord, nous allons configurer l' datastoreutilisation de Strapi. Veuillez noter que vous devez avoir installé Node.js pour exécuter l'application localement. Vous avez également la possibilité d'installer du fil , mais si vous n'avez pas de fil, veuillez utiliser le à la npmplace.

L' datastoreutilisationStrapi

Strapi fournit un tas de modèles pour démarrer rapidement avec l'application. Comme notre magasin de chaussures est une application de commerce électronique, nous utiliserons le ecommercemodèle pour créer le fichier datastore.

Pour cela, il suffit de créer un shoesdossier et d'ouvrir une invite de commande (ou un terminal) sur le répertoire shoes.

Maintenant, utilisez la commande suivante pour créer un projet Strapi :

yarn create strapi-app datastore --template ecommerce

Veuillez noter que nous avons fourni un nom de projet datastoreet le modèle comme ecommercedans la commande ci-dessus.

La commande prendra un certain temps pour télécharger les dépendances requises, les installer et les configurer pour vous. Cependant, une fois cela fait, l'application Strapi sera accessible sur votre navigateur en utilisant l'URL [localhost:1337](http://localhost:1337).

Il est également important de se rappeler que vous devez enregistrer votre profil pour la première fois pour créer vos informations d'identification. Ces mêmes informations d'identification seront utilisées pour s'authentifier dans Strapi, veuillez donc prendre le temps de remplir les informations obligatoires et de vous inscrire.

1-strapi-initial.png

Après votre inscription, vous arriverez sur la page d'accueil de Strapi. Cela vous donnera les indications dont vous avez besoin pour créer la structure de contenu, rejoindre des communautés et remplir de nombreuses autres fonctions.

2-admin-panel.png

Créer des types

Nous allons maintenant commencer à créer le typesdans Strapi. Vous pouvez considérer ces types comme des tables avec un schéma dans la base de données relationnelle.

Pour notre application, nous voulons créer des données de chaussures en tant que Producttype. Chaque produit de chaussure aura ses propres méta-informations, comme le nom, le prix, la description, le stock, la catégorie et la société.

Nous allons également gérer Categoryet Companyen tant que types indépendants et créer des relations avec le Producttype.

Alors, commençons à créer les types un par un. Tout d'abord, créez les champs suivants pour le Categorytype :

  • name : Un champ de type texte.
  • slug : un fragment d'URL pour identifier cette catégorie. C'est de type UID

Capture d'écran 2022-07-14 à 21.22.40.png

De même, vous pouvez créer un type de société avec les champs nom et slug.

Capture d'écran 2022-07-14 à 21h49.27.png

Et maintenant, nous allons créer le type de produit, avec les champs indiqués dans l'image ci-dessous.

Capture d'écran 2022-07-04 à 15h55.56.png

La plupart des champs ci-dessus sont explicites. Cependant, quelques champs nécessitent des explications.

  • image : Il s'agit de l'image du produit, et le type est Media. Dans Strapi, vous pouvez télécharger des ressources (images, vidéos, fichiers) dans la médiathèque pour les utiliser plus tard.
  • les catégories et la société se rapportent aux types respectifs que nous avons déjà créés.
  • statut : Un champ indique le statut du produit.
  • stock : Un champ numérique contient l'enregistrement du nombre de chaussures en stock.

Insérer des données

Comme tous les types requis sont maintenant créés, nous pouvons commencer à créer des exemples de données dans Strapi. Tout d'abord, téléchargeons quelques images de chaussures sympas. Vous pouvez les collecter à partir d'un site Web multimédia comme unsplashet télécharger des éléments à partir du Media Librarymenu.

Capture d'écran 2022-07-04 à 3.56.38 PM.png

Ensuite, parcourez l'option Content Manager dans la navigation de gauche et commencez à créer des entrées pour le type de catégorie. Vous pouvez créer les catégories mentionnées dans l'image ci-dessous, ou n'hésitez pas à créer les vôtres.

Capture d'écran 2022-07-04 à 3.57.05 PM.png

De même, insérez des entrées pour les données de l'entreprise.Capture d'écran 2022-07-04 à 3.57.22 PM.png

Enfin, entrez les données pour le type de produit.

Capture d'écran 2022-07-04 à 4.07.19 PM.png

Jetons d'API

Jusqu'à présent, nous avons créé tout le contenu requis dans Strapi et sommes sur le point d'utiliser tous les éléments de l'interface utilisateur, avec les API Strapi. Vous pouvez accéder aux API Strapi en utilisant REST vers GraphQL, mais n'oubliez pas que vous devez obtenir un jeton d'API pour effectuer des appels d'API réussis.

Cliquez sur Paramètres> Paramètres globaux> Jetons API dans la barre de navigation de gauche, puis cliquez sur le Create new API Tokenbouton pour créer un jeton d'accès complet pour l'application chaussures. Veuillez garder ce jeton en sécurité avec vous, car nous l'utiliserons sous peu.

Capture d'écran 2022-07-04 à 4.07.45 PM.png

L' clientutilisationGatsby

Nous avons réussi à configurer le datastoreavec Strapi, et il est maintenant temps de configurer le clientcôté avec Gatsby.

Pour ce faire, ouvrez une autre invite de commande/terminal dans le dossier racine du projet et exécutez la commande suivante.

yarn global add gatsby-cli

Cette commande installera globalement l'interface de ligne de commande (CLI) Gatsby. Cela nous aide à interagir avec le framework Gatsby pour effectuer différentes tâches.

Tout comme Strapi, Gatsby est livré avec plusieurs modèles pour créer un projet. Dans le monde Gatsby, ceux-ci sont appelés "modèles de démarrage". Nous utiliserons le modèle de démarrage par défaut pour créer le projet et nommer le fichier client.

Veuillez exécuter la commande suivante pour créer le projet Gatsby.

npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default

La commande ci-dessus prendra un certain temps et créera la structure du projet pour vous. Maintenant, accédez au clientrépertoire et démarrez l'application localement à l'aide de la gatsby developcommande.

cd client
gatsby develop

L'application Gatsby s'exécutera sur l' [localhost:8000](http://localhost:8000)URL et vous verrez une interface utilisateur comme celle-ci lorsque vous y accéderez à l'aide de votre navigateur. Il s'agit d'une page par défaut du modèle de démarrage que nous avons utilisé. Nous le changerons bientôt.

Capture d'écran 2022-07-04 à 4.28.49 PM.png

Gatsby et Strapi : Une meilleure histoire ensemble

Nous allons donc maintenant réunir Gatsby et Strapi pour donner forme à notre application. Nous appellerons les API Strapi de Gatsby et récupérerons les données des chaussures au moment de la construction.

L'écosystème de plug-ins Gatsby a un plug-in source appelé gatsby-source-strapiqui aide à récupérer les données de Strapi à l'aide de GraphQL. Installons ce plug-in et quelques autres dépendances pour gérer les images et la transformation. Veuillez exécuter la commande suivante à partir du terminal dans le clientrépertoire.

yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp

Créez un fichier appelé .env.developmentà la racine du clientdossier, avec le contenu suivant.

STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337

Voici le <STRAPI-API-TOKEN>jeton que vous avez copié lors de la configuration du magasin de données Strapi. Vous pouvez maintenant importer le clientprojet dans votre éditeur de code préféré (comme VS Code dans mon cas).

Maintenant, ouvrez le gatsby-config.jsfichier et remplacez le contenu par le contenu ci-dessous. Il s'agit d'un fichier de configuration qui définit les métadonnées du site et les options de plug-in.

Examinez de plus près les options que nous avons définies pour le gatsby-source-strapiplug-in : nous avons spécifié l'URL de l'API Strapi, le jeton d'API et le nom des types de collection avec lesquels nous voulons interagir.

require("dotenv").config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  siteMetadata: {
    title: `Shoes`,
    description: `The one stop shop for your shoes and footwear needs.`,
    author: `@tapasadhikary`,
    siteUrl: `https://shoes.io/`,
  },
  plug-ins: [
    "gatsby-plugin-gatsby-cloud",
    {
      resolve: "gatsby-source-strapi",
      options: {
        apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
        accessToken: process.env.STRAPI_TOKEN,
        collectionTypes: [
          {
            singularName: "product",
          },
          {
            singularName: "company",
          },
          {
            singularName: "category",
          },
        ],
      },
    },
    "gatsby-plugin-image",
    "gatsby-plugin-sharp",
    "gatsby-transformer-sharp",
    "gatsby-transformer-remark",
  ],
}

Veuillez arrêter et redémarrer la gatsby developfonction et accéder à l'URL http://localhost:8000/__graphqlpour ouvrir l'explorateur GraphQL de Gatsby.

Gatsby fournit l'explorateur GraphQL en tant qu'outil de développement, ce qui vous permet de créer facilement les requêtes GraphQL. Vous devez localiser tous les types de collection Strapi dans la Explorercolonne la plus à gauche : ils commencent tous par le texte allStrapi.

Bon, essayons maintenant de créer un exemple de requête pour la allStrapiProductcollection. Vous pouvez développer la collection et sélectionner les champs pour lesquels vous souhaitez récupérer les données ; vous verrez une requête GraphQL créée automatiquement, en fonction de votre sélection.

Vous pouvez maintenant exécuter la requête en appuyant sur le bouton "Exécuter" dans l'en-tête du panneau du milieu. Vous pouvez trouver la sortie dans le panneau le plus à droite.

Je vous suggère de passer du temps avec l'explorateur GraphQL et de jouer avec les requêtes pour vous y habituer.

Capture d'écran 2022-07-04 à 4.36.51 PM.png

Pour construire les requêtes GraphQL, nous les utiliserons pour créer les composants de l'interface utilisateur. Gatsby est basé sur React, vous pouvez donc utiliser toute la puissance de la bibliothèque React dans Gatsby. Ouvrez simplement le index.jsfichier et remplacez le contenu existant par le code suivant.

// index.js

import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"

import { useStaticQuery, graphql } from "gatsby"

import '../style/shoes.css'

const IndexPage = () => {
  const { allStrapiProduct } = useStaticQuery(graphql`
    query {
      allStrapiProduct(sort: {order: ASC, fields: title}) {
        edges {
          node {
            image {
              url
            }
            slug
            price
            title
            id
            stock
            status
          }
        }
      }
    }
  `)

  return (
    <Layout>
      <Seo title="Home" />
        <ShoeList shoes={allStrapiProduct.edges} />
    </Layout>
  )
}

export default IndexPage

 

Examinons maintenant le code du index.jsfichier. Nous utilisons une requête GraphQL pour récupérer tous les produits triés par titre de produit dans l'ordre croissant. Gatsby nous fournit un hook React appelé useStaticQuerypour effectuer une requête GraphQL.

Ensuite, nous passons le tableau de produits récupéré (chaussures) comme accessoire au ShoeListcomposant. Nous devons créer le composant qui itérera sur le shoestableau et commencer à créer une disposition de carte pour chaque détail de chaussure.

Pour ce faire, veuillez créer un fichier appelé ShowList.jssous le componentsdossier avec le contenu suivant.

// ShoeList.js

import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
  console.log(shoes);
  return (
    <div className="shoe-list">
    {shoes.map((shoe) => (
      <ShoeCard key={shoe.node.id} shoe={shoe.node} />
    ))}
    </div>
  )


}

export default ShoeList

 

Comme vous le remarquez dans le code ci-dessus, nous retirons chaque détail de chaussure et les transmettons comme accessoires à un autre composant, ShoeCard. Vous devez donc créer un fichier appelé ShoeCard.jssous le componentsdossier, avec le contenu suivant.

// ShoeCard.js

import * as React from "react"
import { Link } from "gatsby"

const ShoeCard = ({ shoe }) => {
  return (
    <Link
      to={`/${shoe.slug}`}
      className="shoe-card" >
        <div className="img-container">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>  
        <div className="details">
          <h2>{shoe.title} - ${shoe.price}</h2>
        </div>
    </Link>
  )
}

export default ShoeCard

 

Le composant ShoeCard affiche l'image, le titre et le prix de la chaussure. Plus tard, nous ne révélerons le titre et le prix que lorsque l'utilisateur survolera une image de chaussure en utilisant les styles CSS.

Notez également que la carte de chaussures est enveloppée d'un fichier Link. Le composant Link provient de Gatsby et nous aide à établir un lien entre les pages d'une application Gatsby. Le composant Lien a un attribut que nous utilisons pour créer un lien vers une page de destination. Dans l'exemple ci-dessus, la valeur de l'attribut est la valeur de slug de chaque chaussure.

Nous avons l'intention d'accéder à une nouvelle page lorsque l'utilisateur clique sur une carte de chaussures ; cette nouvelle page affichera plus de détails sur une chaussure et les options d'achat. Mais nous devons faire quelques changements, et nous le ferons plus tard. Tout d'abord, nous devons nous concentrer sur la préparation de la page de liste de chaussures avec tout le style.

Modifions un peu les composants Layout et Header. Tout d'abord, remplacez le contenu du layout.jsfichier par le contenu suivant. Il est assez similaire au fichier layout.js existant fourni avec le modèle, mais nous avons apporté quelques modifications mineures au style.

// layout.js

import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"

import Header from "./header"
import "./layout.css"

const Layout = ({ children }) => {
  const data = useStaticQuery(graphql`
    query SiteTitleQuery {
      site {
        siteMetadata {
          title
        }
      }
    }
  `)

  return (
    <>
      <Header siteTitle={data.site.siteMetadata?.title || `Title`} />
      <div className="container">
        <main className="content">{children}</main>
        <footer>
          © {new Date().getFullYear()} &middot; Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
        </footer>
      </div>
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

 

Voici le contenu du Header.jsfichier que vous devez remplacer dans le fichier existant.

// Header.js

import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"

const Header = ({ siteTitle }) => (
  <header>
    <Link to="/" className="logo">
    👠 {siteTitle}
    </Link>
  </header>
)

Header.propTypes = {
  siteTitle: PropTypes.string,
}

Header.defaultProps = {
  siteTitle: ``,
}

export default Header

Maintenant, créons un styledossier sous le srcrépertoire. Pour ce faire, créez un shoes.cssfichier sous le styledossier avec le contenu suivant.

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");

*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  scroll-behavior: smooth;
}
html {
  overflow: auto;
}

body {
  height: 100vh;
  background-color: rgb(3, 28, 34);
  color: #ffffff;
  font-family: "Poppins", sans-serif;
}

a {
  text-decoration: none;
  color: #ffffff;
}

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #282d2e;
  padding-left: 0.5rem;
  padding-right: 0.5rem;
  margin: 0 0 0.5rem 0;
}

header .logo {
  font-size: 2rem;
  font-weight: 500;
  color: #ffffff;
  padding: 0.5rem;
}

footer {
  width: 100%;
  padding: 0.3rem;
  background-color: #282d2e;
  text-align: center;
}

footer > a {
  color: #1af41a;
  text-decoration: underline;
}

.btn {
  padding: 10px;
  cursor: pointer;
  font-size: 18px;
  border: none;
  border-radius: 10px;
}

.btn.btn-primary {
  background-color: #40ee10;
  color: #000000;
}

.btn.btn-primary:hover {
  background-color: #70e007;
  color: #000000;
}

.btn.btn-secondary {
  background-color: #ffffff;
  color: #282d2e;
}

.btn.btn-secondary:hover {
  background-color: #282d2e;
  color: #ffffff;
}

.container {
  height: calc(100vh - 73px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.content {
  flex-grow: 1;
  overflow: auto;
}

.shoe-list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.shoe-card {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  width: 15rem;
  height: 15rem;
  margin: 1.2rem;
}

.shoe-card .img-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  transition: all 0.5s ease-in-out;
}

.shoe-card .img-container > IMG {
  width: 15rem;
  height: 15rem;
  object-fit: cover;
  resize: both;
  border-radius: 10px;
}

.shoe-card:hover .img-container {
  transform: translate(-1rem, -1rem);
}

.shoe-card:hover .details {
  transform: translate(1rem, 1rem);
}

.shoe-card .details {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding: 0.5rem;
  display: flex;
  background-color: #fff;
  z-index: 1;
  align-items: flex-end;
  transition: 0.5s ease-in-out;
  line-height: 1rem;
  border-radius: 10px;
}

.shoe-card .details h2 {
  display: block;
  font-size: 1rem;
  color: #000000;
  font-weight: 500;
}

Et c'est tout!

Exécutez maintenant l'application localement en utilisant l'URL [http://localhost:8000](http://localhost:8000)et vous verrez la liste des images de chaussures sur la page. Passez votre souris sur les images de chaussures et une animation révélera le nom de la chaussure et le prix.

liste-de-chaussures.png

C'est génial. Alors maintenant, essayez de cliquer sur l'une des cartes de chaussures.

Aie! vous obtenez une page comme ci-dessous, et elle semble cassée. Il a essayé de naviguer vers une page identifiée par la valeur de slug de la chaussure, sans succès.

Mais pas de soucis, nous pouvons résoudre le problème.

Capture d'écran 2022-07-11 à 21h44.03.png

Gatsby peut créer des pages au moment de la construction à l'aide de modèles. Ceux-ci exploitent la même structure d'interface utilisateur que vous souhaitez utiliser pour un ensemble de données différent.

Par exemple, dans notre shoesapplication, nous souhaitons afficher les détails de chacune des chaussures. La structure de la page de détails sera la même, mais les données de la chaussure changeront en fonction de l'image de la chaussure sur laquelle nous cliquons.

Ainsi, nous pouvons créer un modèle appelé shoe-details.jssous le src/templatesdossier avec le contenu suivant.

// shoe-details.js

import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"

export default function ShoeDetails({ data }) {
  const shoe = data.strapiProduct
  const [quantity, setQuantity] = useState(1)
  return (
    <Layout>
      <div className="shoe-details">
        <div className="cover">
          <img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
        </div>
        <div className="info">
          <div className="info-heading">
            <h2>{shoe.title}</h2> 
            <Link to={`/category/${shoe.categories[0].slug}`}>
              <span>{shoe.categories[0].name}</span>
            </Link> { ' '}
            from {' '}
            <Link to={`/company/${shoe.company.slug}`}>
              {shoe.company.name}
            </Link>
          </div>

          <div className="info-body">
            <p>{shoe.description}</p>
            <span>${shoe.price} per unit</span> { ' - '}
            <>
              {
                shoe.stock > 0 ?
                  <span>{shoe.stock} In Stock</span> :
                  <span>Out of Stock</span>
              }
            </>
          </div>

          <div className="info-purchase">
            {
              shoe.stock > 0 ?
              <>
                <p>
                  I want to purchase {' '}
                  <input 
                    type="number" 
                    min="1" 
                    max={shoe.stock} 
                    value={quantity}
                    onChange={(e) => setQuantity(e.target.value)}
                    /> {' '} unit
                </p>
                <p className="price">Total Price: ${quantity * shoe.price}</p>
                <button className="btn btn-primary">Add to Cart</button>
              </> :
              <>
                <p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
                <button className="btn btn-secondary">Notify Me!</button>
              </>
            }

          </div>

        </div>
      </div>  
    </Layout>
  )
}

export const query = graphql`
  query($slug: String!) {
    strapiProduct(slug: {eq: $slug}) {
      id
      title
      price
      status
      stock
      categories {
        name
        slug
      }
      company {
        name
        slug
      }
      description
      image {
        url
      }
      updatedAt
    }
  }
`

 

Dans le code ci-dessus, nous effectuons une requête GraphQL pour récupérer les détails d'un produit (chaussure) en fonction de la valeur du slug.

Nous pouvons utiliser les détails du produit pour construire la structure lorsque nous récupérons les détails du produit. Dans ce cas, la structure comprend la photo du produit et des informations telles que la catégorie, l'entreprise, le prix et le stock. La page comprend également la zone de saisie du numéro pour spécifier la quantité de chaussures nécessaires et calculer automatiquement le montant total à payer pour un paiement.

Tout cela est formidable, mais comment obtenir la valeur de slug de la chaussure et la mapper avec le shoe-detailsmodèle ? Essayons de le faire maintenant.

Ouvrez le gatsby-node.jsfichier et remplacez le contenu par le code suivant :

// gatsby-node.js

exports.createPages = async function ({ actions, graphql }) {
  const { data } = await graphql(`
    query {
      allStrapiProduct {
        edges {
          node {    
            slug
          }
        }
      }
    }
  `)
  data.allStrapiProduct.edges.forEach(edge => {
    const slug = edge.node.slug
    actions.createPage({
      path: slug,
      component: require.resolve(`./src/templates/shoe-details.js`),
      context: { slug: slug },
    })
  })
}

Gatsby exécute le gatsby-node.jsfichier au moment de la construction. Ici, nous récupérons les slugs pour tous les produits, nous pouvons ensuite intégrer les slugs et créer des pages pour chacun d'eux.

La createPageméthode prend un objet comme argument où nous fournissons les détails du chemin référencé avec le slug et mappons à quel composant. Veuillez noter que le composant est le fichier de modèle que nous avions vu ci-dessus. Nous transmettons également les données de contexte qui sont le slug lui-même.

Ainsi, chaque chemin avec la valeur slug est maintenant mappé au fichier de modèle, avec la valeur slug transmise comme contexte. Nous avons déjà appris comment le composant de modèle utilise cette valeur de slug et récupère les détails du produit. J'espère que tous les points sont bien connectés maintenant.

Ouvrez maintenant le shoes.cssfichier et ajoutez les styles suivants sous ceux existants. Les styles suivants sont pour la page des détails de la chaussure.

.shoe-details {
  padding: 1rem;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.shoe-details .cover {
  display: flex;
  align-content: center;
  justify-content: center;
}

.shoe-details .cover > IMG {
  width: 30rem;
  height: 30rem;
  border-radius: 50%;
}

.shoe-details .info-heading {
  margin-bottom: 1rem;
}

.shoe-details .info-heading > a {
  color: #1af41a;
  text-decoration: underline;
}

.shoe-details .info-heading > H2 {
  font-size: 3rem;
}

.shoe-details .info-body > P {
  margin: 0;
}

.shoe-details .info-body > SPAN {
  font-size: 1.5rem;
}

.shoe-details .info-purchase {
  margin: 2rem 0 0 0;
  border: 1px solid #4a4545;
  border-radius: 5px;
  padding: 1rem;
  background-color: black;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.shoe-details .info-purchase .price {
  font-size: 1.5rem;
  font-weight: 500;
  color: #ffffff;
}

.shoe-details .info-purchase INPUT {
  border: 1px solid #ececec;
  padding: 5px;
  border-radius: 3px;
  font-size: 1rem;
}

.shoe-filtered-list H2 {
  font-size: 2rem;
  font-weight: 500;
  color: #1af41a;
  margin: 0 0 1rem 1rem;
}

@media only screen and (max-width: 900px) {
  .shoe-details {
    padding: 1rem;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
}

@media only screen and (max-width: 600px) {
  .shoe-details .cover > IMG {
    width: 20rem;
    height: 20rem;
  }
}

Maintenant, redémarrez le serveur local de Gatsby et accédez à nouveau à l'application sur localhost:8000. Cliquez sur l'une des cartes de chaussures ; vous devriez voir une page élégante, rendue avec des détails de chaussures.

détails-chaussures.png

Ok, c'est tout ce que nous voulions construire avec Gatsby et Strapi : un magasin de chaussures Jamstack avec quelques pages servies statiquement. Et nous l'avons fait !

Cependant, ne vous inquiétez pas : vous pouvez aller bien plus loin d'ici. Vous pouvez créer des modèles pour les catégories et les entreprises et avoir des pages pour chacune. Vous pouvez développer des fonctions de recherche et créer des options de filtrage pour les chaussures par titre, gamme de prix, entreprise et catégorie. Le code du projet est open source sous licence MIT sur GitHub.

Pour un bref récapitulatif, regardez la vidéo de démonstration rapide ci-dessous. Il s'agit d'une démo de l' shoesapplication que nous avons construite dans cet article, ainsi que de quelques fonctionnalités supplémentaires mentionnées ci-dessus.

Lien : https://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi

#ecommerce #gatsby #strapi #javascript

Comment Créer Votre Boutique En Ligne Avec Gatsby Et Strapi
Diego  Elizondo

Diego Elizondo

1658819367

4 Formas De Crear Un Panel De Administración De Strapi Personalizado

Hace unos meses comencé un proyecto como ingeniero de software en el que usábamos Strapi V3.

Para aquellos que no están familiarizados con Strapi, es un CMS (Sistema de gestión de contenido) de código abierto y autónomo que permite a los usuarios crear, gestionar y exponer datos gracias a un Panel de administración integrado.

En mi proyecto, rápidamente comenzamos a personalizar el Panel de administración de Strapi anulando directamente los archivos en nuestro proyecto: solo teníamos que reproducir la ruta al archivo específico que queríamos modificar.

Puede pensar en ello como si quisiera expulsar un archivo específico que necesita ser modificado. Por ejemplo, si quiero cambiar el color del botón "Publicar/Cancelar publicación" de azul a verde, tengo que:

  1. Encuentre dónde se maneja el color del botón en el repositorio de Github de Strapi V3 . Está en el archivo: packages/strapi-plugin-content-manager/admin/src/containers/EditView/Header/index.js . (Este es el archivo que quiero expulsar)
  2. Cree la carpeta relativa al paquete en la carpeta de extensiones, /extensions/content-manager/
  3. Vuelva a crear la ruta = cree el archivo index.js: extensiones/content-manager/admin/src/containers/EditView/Header/index.js
  4. Copie y pegue el archivo anterior (desde el repositorio o los módulos del nodo)
  5. Reemplace "principal" por "éxito" en la línea 13

Luego, al crear el panel de administración de Strapi, Strapi sabría que este archivo se había modificado y usaría este en lugar del anterior. Y así, el botón Publicar/Despublicar es verde.

¡Entonces Strapi V4 estaba en vivo! Y en Strapi V4, esta funcionalidad ya no está disponible.

Así que rápidamente me pregunté si todavía sería posible personalizar la interfaz de nuestro Strapi. En este artículo, le presentaré cuatro formas de personalizar su panel de administración de Strapi, comenzando con la más fácil: el uso de un complemento ya existente. Luego la técnica de opciones de configuración, seguido del método de inyección de archivos, para terminar con el más complejo: la creación de tu propio plugin.

gifs de harry potter

Para ilustrar, estoy tomando el ejemplo de un medio: los escritores necesitan un CMS para escribir, editar y publicar sus artículos y eligieron Strapi V4.

Complemento existente

Lo primero y más fácil de hacer cuando desea personalizar algo en la interfaz de su Strapi es intentar encontrar un complemento que haga lo que desea.

Para encontrar complementos, puede buscar en:

En mi caso, los editores no son grandes fans de la sintaxis markdown utilizada en RichText Object de Strapi V4, agradecerían algo más realista para ver directamente el resultado sin tener que usar el modo de vista previa.

Encontré el complemento "strapi-plugin-editorjs", que es un complemento de EditorJS para que Strapi reemplace el campo RichText que ofrece Strapi. La documentación es muy clara sobre cómo instalar y usar el complemento.

Lo único que se debe hacer en este caso es:

yarn add strapi-plugin-react-editorjs

Y después de esto, el objeto RichText en el panel de administración de Strapi usa el de EditorJS:

¿Qué sucede si el complemento que quiero no existe?

Opciones de configuración

Primero, puedes modificar muy fácilmente el panel de administración de Strapi gracias a las opciones de configuración: esto se usa para las traducciones, el logotipo, el favicon, los locales disponibles, el tema, los tutoriales e incluso la notificación (ver la documentación aquí ).

Le mostraré rápidamente cómo usarlo con el archivo de traducción y cómo cambiar todos los textos de la interfaz de su Strapi.

Tienes que encontrar la traducción que quieres cambiar: por ejemplo, si quiero cambiar el título de la página de inicio de ”Bienvenido 👋” a “¡Hola, Chloé!”:

💡 Para encontrar fácilmente el archivo de traducción en la carpeta de github: puede reemplazarlo .compor .deven la URL de Github que abre una pestaña de VisualStudio en su pestaña de Internet. Y luego, encuentre directamente la traducción para cambiar gracias al mensaje anterior 💡

// src/admin/app.js

export default {
  config: {
    translations: {
      en: {
        "app.components.HomePage.welcome.again": "Hi Chloé!",
      },
    },
  },
  bootstrap() {},
};

Ya verás:

💡Úselo yarn develop —watch-adminpara ver directamente las modificaciones que está aplicando sin tener que reiniciar su servidor. 💡

Zona de inyección

También es posible personalizar el Panel de administración utilizando la API de zonas de inyección sin tener que generar un complemento con injectContentManagerComponent.

Voy a tomar un ejemplo simple para mostrarle fácilmente cómo agregar un componente personalizado en la interfaz de su Strapi: Quiero agregar un botón en la interfaz de Strapi que está imprimiendo "Hello World"

Primero cree la /extensionscarpeta src/adminy luego puede crear su componente:

// src/admin/extensions/components/HelloWorldButton/index.js

import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";

const HelloWorldButton = () => {
  return (
    <Button
      variant="secondary"
      startIcon={<Up />}
      onClick={() => alert("Hello World")}
    >
      Hello World
    </Button>
  );
};

export default HelloWorldButton;

Y luego use el injectContentManagerComponentarchivo app.js para inyectar su nuevo componente directamente en su aplicación:

// src/admin/app.js

import HelloWorldButton from "./extensions/components/HelloWorldButton";

export default {
  bootstrap(app) {
    app.injectContentManagerComponent("listView", "actions", {
      name: "HelloWorldButton",
      Component: HelloWorldButton,
    });
  },
};

Que está haciendo eso:

Puede elegir dónde colocar su componente gracias a los dos primeros parámetros del injectContentManagerComponent:

Este ejemplo de inyección puede parecer un poco inútil, así que quiero presentarles un caso de uso en el que lo usé.

En mi caso, tengo una página de inicio donde se destacan algunos artículos. Estos artículos son elegidos por mis editores gracias a una relación con mi colección de “Artículos”.

Solo quiero ver en mi página de inicio los artículos que están publicados y no los que están redactados. Desafortunadamente, el selector utilizado para hacer la relación con la colección “Artículo” permite elegir entre todos los artículos (incluso los redactados). Mis redactores piensan que puede ser peligroso porque aunque haya un puntito de color que indique que aún no está publicado, es posible que algún día alguien se equivoque y ponga en portada un borrador de artículo.

En mi proyecto, he creado un componente que usa el selector nativo de Strapi pero he agregado un check para permitir que el usuario seleccione solo los artículos publicados.

NB: también puede usar este método para inyectar un componente de un complemento específico en otro utilizando el métodoinjectComponent()que funciona de la misma manera queinjectContentManagerComponent()(documentación aquí )

¿Nuevo complemento?

Si lo que quiere hacer es más complejo que las traducciones o agregar componentes a la interfaz de Strapi, probablemente tendrá que crear su propio complemento. Le recomiendo que lea este artículo o vea este video que son básicamente tutoriales sobre cómo crear su propio complemento.

Esta solución es más compleja y llevará mucho más tiempo que las otras dos soluciones. Si puede, es mejor utilizar la zona de inyección para ahorrar algo de tiempo.

Conclusión

Incluso si era globalmente más fácil y rápido personalizar el panel de administración de Strapi usando Strapi V3, no era muy estable. Este método puede verse como una expulsión de archivos: básicamente se trata de tomar un código de Strapi y reescribirlo en su propio código base, lo que crea una fuerte relación entre una biblioteca externa (Strapi) y su propio código. En cada nueva versión de Strapi, si un archivo cambiaba, también tenía que cambiar su código y encontrar dónde hacerlo y cómo hacerlo. No era muy fácil de mantener y podría romper muchas cosas si hubiera hecho muchas modificaciones.

En Strapi V4, todavía hay una conexión entre Strapi y su base de código si, por ejemplo, está reutilizando el componente de Strapi (como hice en mi ejemplo de inyección). Pero la conexión es mucho más pequeña y sus modificaciones son más estables. La elección de Strapi de eliminar el método de expulsión parece pragmática para mantener su aplicación más fácilmente.

Fuente: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/

#strapi 

4 Formas De Crear Un Panel De Administración De Strapi Personalizado

4 Maneiras De Criar Um Painel De Administração Strapi Personalizado

Há alguns meses, iniciei um projeto como engenheiro de software no qual usávamos o Strapi V3.

Para aqueles que não estão familiarizados com o Strapi, é um CMS (Sistema de Gerenciamento de Conteúdo) de código aberto e headless que permite aos usuários criar, gerenciar e expor dados graças a um painel de administração integrado.

No meu projeto, começamos rapidamente a personalizar o painel de administração do Strapi substituindo diretamente os arquivos em nosso projeto: apenas precisávamos reproduzir o caminho para o arquivo específico que queríamos modificar.

Você pode pensar nisso como se quisesse ejetar um arquivo específico que precisa ser modificado. Por exemplo, se eu quiser mudar a cor do botão “Publicar/Cancelar publicação” de azul para verde, eu tenho que:

  1. Encontre onde a cor do botão é tratada no repositório Github do Strapi V3 . Está no arquivo: packages/strapi-plugin-content-manager/admin/src/containers/EditView/Header/index.js . (Este é o arquivo que eu quero ejetar)
  2. Crie a pasta relativa ao pacote na pasta de extensões, /extensions/content-manager/
  3. Recrie o caminho = crie o arquivo index.js: extensions/content-manager/admin/src/containers/EditView/Header/index.js
  4. Copie e cole o arquivo antigo (do repositório ou dos módulos do nó)
  5. Substitua "primário" por "sucesso" na linha 13

Então, ao construir o Strapi Admin Panel, Strapi saberia que este arquivo havia sido modificado e usaria este em vez do antigo. E assim, o botão Publicar/Cancelar publicação fica verde.

Então Strapi V4 fez uma transmissão ao vivo! E no Strapi V4, essa funcionalidade não está mais disponível.

Então eu rapidamente me perguntei se ainda seria possível personalizar a interface do nosso Strapi. Neste artigo, apresentarei quatro maneiras de personalizar seu painel de administração do Strapi, começando pela mais fácil: o uso de um plugin já existente. Em seguida, a técnica de opções de configuração, seguida do método de injeção de arquivos, para finalizar com a mais complexa: a criação do seu próprio plugin.

harry potter gif

Para ilustrar, tomo o exemplo de uma mídia: os escritores precisam de um CMS para escrever, editar e publicar seus artigos e escolheram o Strapi V4.

Plug-in existente

A primeira e mais fácil coisa a fazer quando você deseja personalizar algo na interface do seu Strapi é tentar encontrar um plugin que faça o que você deseja.

Para encontrar plugins, você pode pesquisar:

No meu caso, os editores não são grandes fãs da sintaxe markdown usada no RichText Object do Strapi V4, eles gostariam de algo mais realista para ver diretamente o resultado sem precisar usar o modo de visualização.

Encontrei o plugin "strapi-plugin-editorjs" que é um plugin EditorJS para Strapi para substituir o campo RichText oferecido pelo Strapi. A documentação é muito clara sobre como instalar e usar o plugin.

A única coisa a fazer neste caso é:

yarn add strapi-plugin-react-editorjs

E depois disso, o objeto RichText no Strapi Admin Panel usa o EditorJS:

E se o plugin que eu quero não existir?

Opções de configuração

Primeiro, você pode modificar muito facilmente o painel de administração do Strapi graças às opções de configuração: isso é usado para as traduções, o logotipo, o favicon, as localidades disponíveis, o tema, os tutoriais e até a notificação (consulte a documentação aqui ).

Vou mostrar rapidamente como usá-lo com o arquivo de traduções e como alterar todas as palavras da interface do seu Strapi.

Você precisa encontrar a tradução que deseja alterar: por exemplo, se eu quiser alterar o título da página inicial de ”Bem-vindo 👋” para “Oi Chloé!”:

💡 Para encontrar facilmente o arquivo de tradução na pasta do github: você pode substituir .compor .devna URL do Github que abre uma guia do VisualStudio na sua guia de internet. E então, encontre diretamente a tradução para mudar graças à mensagem antiga 💡

// src/admin/app.js

export default {
  config: {
    translations: {
      en: {
        "app.components.HomePage.welcome.again": "Hi Chloé!",
      },
    },
  },
  bootstrap() {},
};

Você verá:

💡Use yarn develop —watch-adminpara ver diretamente as modificações que você está aplicando sem precisar reiniciar seu servidor. 💡

Zona de injeção

Também é possível personalizar o Painel Administrativo usando a API de zonas de injeção sem precisar gerar um plugin com injectContentManagerComponent.

Vou dar um exemplo simples para mostrar facilmente como adicionar um componente personalizado na interface do seu Strapi: Eu quero adicionar um botão na interface do Strapi que está imprimindo “Hello World”

Primeiro crie a /extensionspasta src/admine então você pode criar seu componente:

// src/admin/extensions/components/HelloWorldButton/index.js

import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";

const HelloWorldButton = () => {
  return (
    <Button
      variant="secondary"
      startIcon={<Up />}
      onClick={() => alert("Hello World")}
    >
      Hello World
    </Button>
  );
};

export default HelloWorldButton;

E, injectContentManagerComponentem seguida, use o arquivo app.js para injetar seu novo componente diretamente em seu aplicativo:

// src/admin/app.js

import HelloWorldButton from "./extensions/components/HelloWorldButton";

export default {
  bootstrap(app) {
    app.injectContentManagerComponent("listView", "actions", {
      name: "HelloWorldButton",
      Component: HelloWorldButton,
    });
  },
};

Que está fazendo isso:

Você pode escolher onde colocar seu componente graças aos dois primeiros parâmetros do injectContentManagerComponent:

Este exemplo de injeção pode parecer um pouco inútil, então quero apresentar um caso de uso em que eu o usei.

No meu caso, tenho uma página inicial que destaca alguns artigos. Estes artigos são escolhidos pelos meus editores graças a uma relação com a minha coleção “Artigos”.

Eu só quero ver na minha página inicial os artigos que são publicados e não os que são redigidos. Infelizmente, o seletor utilizado para fazer a relação com a coleção “Artigo” permite que o usuário escolha entre todos os artigos (mesmo os redigidos). Meus escritores pensam que pode ser perigoso porque mesmo que haja um pequeno ponto de cor indicando que ainda não foi publicado, é possível que um dia alguém cometa um erro e coloque na página inicial um rascunho de artigo.

No meu projeto, criei um componente que usa o seletor nativo do Strapi, mas adicionei uma verificação para permitir que o usuário selecione apenas os artigos publicados.

NB: Você também pode usar este método para injetar um componente de um plugin específico em outro usando o métodoinjectComponent()que funciona da mesma forma queinjectContentManagerComponent()(documentação aqui )

Novo plug-in?

Se o que você quer fazer é mais complexo do que traduções ou adicionar componentes na interface do Strapi, você provavelmente terá que criar seu próprio plugin. Eu recomendo que você leia este artigo ou veja este vídeo que são basicamente tutoriais sobre como criar seu próprio plugin.

Esta solução é mais complexa e levará muito mais tempo do que as outras duas soluções. Se puder, é melhor usar a zona de injeção para economizar tempo.

Conclusão

Mesmo que fosse globalmente mais fácil e rápido personalizar o Strapi Admin Panel usando o Strapi V3, não era muito estável. Este método pode ser visto como uma ejeção de arquivo: é basicamente pegar algum código do Strapi e reescrevê-lo em sua própria base de código, o que cria uma forte relação entre uma biblioteca externa (Strapi) e seu próprio código. A cada nova versão do Strapi, se um arquivo fosse alterado, você também precisava alterar seu código e descobrir onde e como fazê-lo. Não era muito fácil de manter e poderia quebrar muitas coisas se você tivesse feito muitas modificações.

No Strapi V4, ainda há uma conexão entre o Strapi e sua base de código se, por exemplo, você estiver reutilizando o componente do Strapi (como fiz no meu exemplo de injeção). Mas a conexão é bem menor e suas modificações são mais estáveis. A escolha do Strapi para remover o método de ejeção parece pragmática para manter seu aplicativo com mais facilidade.

Fonte: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/

#strapi 

4 Maneiras De Criar Um Painel De Administração Strapi Personalizado
山岸  英樹

山岸 英樹

1658815500

カスタムStrapi管理パネルを作成する4つの方法

数ヶ月前、私はソフトウェアエンジニアとしてStrapiV3を使用するプロジェクトを開始しました。

ストラップに慣れていない人のために、それはオープンソースのヘッドレスCMS(コンテンツ管理システム)であり、ユーザーは組み込みの管理パネルのおかげでデータを作成、管理、公開することができます。

私のプロジェクトでは、プロジェクト内のファイルを直接オーバーライドすることで、Strapiの管理パネルのカスタマイズをすぐに開始しました。変更する特定のファイルへのパスを再現するだけで済みました。

変更が必要な特定のファイルを取り出したいと考えることができます。たとえば、「公開/非公開」ボタンの色を青から緑に変更したい場合は、次のことを行う必要があります。

  1. ストラップV3のGithubリポジトリでボタンの色が処理される場所を見つけます。これはファイルにあります:packages / strapi-plugin-content-manager / admin / src / containers / EditView / Header/index.js。(これは私が排出したいファイルです)
  2. 拡張機能フォルダー/extensions/content-manager/にパッケージに関連するフォルダーを作成します。
  3. パスを再作成する=index.jsファイルを作成する:extensions / content-manager / admin / src / containers / EditView / Header / index.js
  4. 古いファイルをコピーして貼り付けます(リポジトリまたはノードモジュールから)
  5. 13行目の「primary」「success」に置き換えます

次に、Strapi管理パネルを作成すると、Strapiはこのファイルが変更されたことを認識し、古いファイルの代わりにこのファイルを使用します。そのため、[公開/非公開]ボタンは緑色です。

その後、Strapi V4がライブになりました!また、Strapi V4では、この機能は使用できなくなりました。

それで、私はすぐに、Strapiのインターフェースをカスタマイズすることはまだ可能かどうか疑問に思いました。この記事では、Strapi管理パネルをカスタマイズする4つの方法を紹介します。最も簡単な方法、つまり既存のプラグインの使用から始めます。次に、構成オプションの手法、続いてインジェクションファイル方式を使用して、より複雑な手法である独自のプラグインの作成を完了します。

ハリーポッターgif

説明のために、私はメディアの例を取り上げています。ライターは記事を書き、編集し、公開するためにCMSを必要とし、StrapiV4を選択しました。

既存のプラグイン

あなたがStrapiのインターフェースで何かをカスタマイズしたいときに最初にそして最も簡単なことはあなたが望むことをするプラグインを見つけようとすることです。

プラグインを見つけるには、以下を調べることができます。

私の場合、編集者は、Strapi V4のリッチテキストオブジェクトで使用されるマークダウン構文の大ファンではありません。プレビューモードを使用せずに、結果を直接表示するためのより現実的なものを高く評価します。

私は、Strapiが提供するRichTextフィールドを置き換えるStrapi用のEditorJSプラグインであるプラグイン「strapi-plugin-editorjs」を見つけました。プラグインのインストール方法と使用方法については、ドキュメントが非常に明確です。

この場合に行う唯一のことは次のとおりです。

yarn add strapi-plugin-react-editorjs

この後、Strapi管理パネルのRichTextオブジェクトはEditorJSオブジェクトを使用します。

必要なプラグインが存在しない場合はどうなりますか?

構成オプション

まず、構成オプションのおかげで、Strapi管理パネルを非常に簡単に変更できます。これは、翻訳、ロゴ、ファビコン、使用可能なロケール、テーマ、チュートリアル、さらには通知にも使用されます(こちらのドキュメントを参照)。

翻訳ファイルでの使用方法と、Strapiのインターフェイスのすべての文言を変更する方法を簡単に説明します。

変更したい翻訳を見つける必要があります。たとえば、ホームページのタイトルを「Welcome👋」から「HiChloé!」に変更したい場合:

💡githubフォルダー内の翻訳ファイルを簡単に見つけるには:インターネットタブにVisualStudioタブを開くGithubURL.comのを.devに置き換えることができます。そして、古いメッセージのおかげで変更する翻訳を直接見つけてください💡

// src/admin/app.js

export default {
  config: {
    translations: {
      en: {
        "app.components.HomePage.welcome.again": "Hi Chloé!",
      },
    },
  },
  bootstrap() {},
};

次のように表示されます。

💡yarn develop —watch-adminサーバーを再起動せずに、適用している変更を直接確認するために使用します。💡

インジェクションゾーン

でプラグインを生成せずに、インジェクションゾーンAPIを使用して管理パネルをカスタマイズすることもできますinjectContentManagerComponent

簡単な例を使用して、Strapiのインターフェイスにカスタムコンポーネントを追加する方法を簡単に示します。「HelloWorld」を印刷しているStrapiのインターフェイスにボタンを追加します。

最初に/extensionsフォルダをsrc/admin作成してから、コンポーネントを作成できます。

// src/admin/extensions/components/HelloWorldButton/index.js

import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";

const HelloWorldButton = () => {
  return (
    <Button
      variant="secondary"
      startIcon={<Up />}
      onClick={() => alert("Hello World")}
    >
      Hello World
    </Button>
  );
};

export default HelloWorldButton;

次にinjectContentManagerComponent、app.jsファイルのを使用して、新しいコンポーネントをアプリに直接挿入します。

// src/admin/app.js

import HelloWorldButton from "./extensions/components/HelloWorldButton";

export default {
  bootstrap(app) {
    app.injectContentManagerComponent("listView", "actions", {
      name: "HelloWorldButton",
      Component: HelloWorldButton,
    });
  },
};

それをしているのは:

injectContentManagerComponent:の最初の2つのパラメーターのおかげで、コンポーネントを配置する場所を選択できます。

この注入の例は少し役に立たないように思われるかもしれないので、私がそれを使用したユースケースを紹介したいと思います。

私の場合、いくつかの記事を紹介するホームページがあります。これらの記事は、私の「記事」コレクションとの関係のおかげで、私の編集者によって選ばれました。

公開されている記事のみをホームページに表示したいので、ドラフトされた記事は表示しません。残念ながら、「Article」コレクションとの関係を行うために使用されるセレクターでは、ユーザーはすべての記事(ドラフトされた記事も含む)から選択できます。まだ公開されていないことを示す色の点が少しあっても、いつか誰かが間違えてホームページにドラフト記事を載せてしまう可能性があるので、筆者は危険だと思っています。

私のプロジェクトでは、Strapiのネイティブセレクターを使用するコンポーネントを作成しましたが、ユーザーが公開された記事のみを選択できるようにするためにチェックを追加しました。

注意:このメソッドを使用して、 (ここのドキュメント)injectComponent()と同じように機能するメソッドをinjectContentManagerComponent()

新しいプラグイン?

やりたいことが翻訳よりも複雑だったり、Strapiのインターフェースにコンポーネントを追加したりする場合は、おそらく独自のプラグインを作成する必要があります。この記事を読むか、このビデオをご覧になることをお勧めします。これらは基本的に、独自のプラグインを作成する方法についてのチュートリアルです。

このソリューションはより複雑で、他の2つのソリューションよりもはるかに時間がかかります。可能であれば、時間を節約するために注入ゾーンを使用することをお勧めします。

結論

ストラップV3を使用してストラップ管理パネルをカスタマイズすることが世界的に簡単かつ迅速であったとしても、それはあまり安定していませんでした。この方法はファイルの排出と見なすことができます。基本的には、Strapiからコードを取得し、それを独自のコードベースで書き直すことで、externライブラリ(Strapi)と独自のコードの間に強い関係を作成します。新しいバージョンのStrapiごとに、ファイルが変更された場合は、コードも変更して、どこでどのように実行するかを見つける必要がありました。それはあまり維持可能ではなく、あなたがたくさんの修正をしたならばそれは多くのことを壊すかもしれません。

ストラップV4では、たとえば、ストラップのコンポーネントを再利用している場合(インジェクションの例で行ったように)、ストラップとコードベースの間に接続があります。ただし、接続ははるかに小さく、変更はより安定しています。アプリをより簡単に維持するために、排出方法を削除するためのストラップの選択は実用的であるように思われます。

出典:https ://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/

#strapi 

カスタムStrapi管理パネルを作成する4つの方法
Anne  de Morel

Anne de Morel

1658815288

4 Façons De Créer Un Panneau D'administration Strapi Personnalisé

Il y a quelques mois, j'ai démarré un projet en tant qu'ingénieur logiciel dans lequel nous utilisions Strapi V3.

Pour ceux qui ne sont pas familiers avec Strapi, il s'agit d'un CMS (Content Management System) open source et sans tête qui permet aux utilisateurs de créer, gérer et exposer des données grâce à un panneau d'administration intégré.

Sur mon projet, nous avons rapidement commencé à personnaliser le panneau d'administration de Strapi en remplaçant directement les fichiers de notre projet : nous n'avions qu'à reproduire le chemin vers le fichier spécifique que nous voulions modifier.

Vous pouvez y penser comme si vous vouliez éjecter un fichier spécifique qui doit être modifié. Par exemple, si je veux changer la couleur d'un bouton « Publier/Dépublier » du bleu au vert, je dois :

  1. Trouvez où la couleur du bouton est gérée dans le référentiel Github de Strapi V3 . Il se trouve dans le fichier : packages/strapi-plugin-content-manager/admin/src/containers/EditView/Header/index.js . (Ceci est le fichier que je veux éjecter)
  2. Créez le dossier relatif au package dans le dossier des extensions, /extensions/content-manager/
  3. Recréez le chemin = créez le fichier index.js : extensions/content-manager/admin/src/containers/EditView/Header/index.js
  4. Copiez-collez l'ancien fichier (depuis le référentiel ou les modules du nœud)
  5. Remplacer "primaire" par "succès" à la ligne 13

Ensuite, lors de la construction du panneau d'administration Strapi, Strapi saurait que ce fichier a été modifié et utiliserait celui-ci à la place de l'ancien. Et donc, le bouton Publier/Dépublier est vert.

Puis Strapi V4 était en direct ! Et dans Strapi V4, cette fonctionnalité n'est plus disponible.

Je me suis donc rapidement demandé s'il serait encore possible de personnaliser l'interface de notre Strapi. Dans cet article, je vais vous présenter quatre façons de personnaliser votre panneau d'administration Strapi, en commençant par la plus simple : l'utilisation d'un plugin déjà existant. Puis la technique des options de configuration, suivie de la méthode du fichier d'injection, pour finir par la plus complexe : la création de votre propre plugin.

gif harry potter

Pour illustrer, je prends l'exemple d'un média : les rédacteurs ont besoin d'un CMS pour rédiger, éditer et publier leurs articles et ils ont choisi Strapi V4.

Plug-in existant

La première et la plus simple chose à faire lorsque vous souhaitez personnaliser quelque chose dans l'interface de votre Strapi est d'essayer de trouver un plugin qui fait ce que vous voulez.

Pour trouver des plugins, vous pouvez consulter :

Dans mon cas, les éditeurs ne sont pas de grands fans de la syntaxe de démarquage utilisée dans l'objet RichText de Strapi V4, ils apprécieraient quelque chose de plus réaliste pour voir directement le résultat sans avoir à utiliser le mode aperçu.

J'ai trouvé le plugin "strapi-plugin-editorjs" qui est un plugin EditorJS pour Strapi pour remplacer le champ RichText proposé par Strapi. La documentation est très claire sur la façon d'installer et d'utiliser le plugin.

La seule chose à faire dans ce cas est :

yarn add strapi-plugin-react-editorjs

Et après cela, l'objet RichText dans le panneau d'administration Strapi utilise celui de EditorJS :

Que faire si le plugin que je veux n'existe pas ?

Possibilités de configuration

Tout d'abord, vous pouvez très facilement modifier le panneau d'administration Strapi grâce aux options de configuration : cela sert aux traductions, au logo, au favicon, aux locales disponibles, au thème, aux tutoriels et même à la notification (voir la documentation ici ).

Je vais vous montrer rapidement comment l'utiliser avec le fichier de traductions et comment changer tous les libellés de l'interface de votre Strapi.

Vous devez trouver la traduction que vous voulez changer : par exemple si je veux changer le titre de la page d'accueil de "Bienvenue 👋" à "Salut Chloé !" :

💡 Pour retrouver facilement le fichier de traduction dans le dossier github : vous pouvez remplacer le .compar .devdans l' URL Github qui ouvre un onglet VisualStudio dans votre onglet internet. Et puis, retrouvez directement la traduction à modifier grâce à l'ancien message 💡

// src/admin/app.js

export default {
  config: {
    translations: {
      en: {
        "app.components.HomePage.welcome.again": "Hi Chloé!",
      },
    },
  },
  bootstrap() {},
};

Tu verras:

💡Utilisez yarn develop —watch-adminafin de voir directement les modifications que vous appliquez sans avoir à relancer votre serveur. 💡

Zone d'injection

Il est également possible de personnaliser le panneau d'administration à l'aide de l'API des zones d'injection sans avoir à générer de plugin avec injectContentManagerComponent.

Je vais prendre un exemple simple pour vous montrer facilement comment ajouter un composant personnalisé dans l'interface de votre Strapi : je veux ajouter un bouton sur l'interface de Strapi qui affiche "Hello World"

Créez d'abord le /extensionsdossier dans src/adminpuis vous pourrez créer votre composant :

// src/admin/extensions/components/HelloWorldButton/index.js

import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";

const HelloWorldButton = () => {
  return (
    <Button
      variant="secondary"
      startIcon={<Up />}
      onClick={() => alert("Hello World")}
    >
      Hello World
    </Button>
  );
};

export default HelloWorldButton;

Puis utilisez le injectContentManagerComponentdans le fichier app.js pour injecter votre nouveau composant directement dans votre application :

// src/admin/app.js

import HelloWorldButton from "./extensions/components/HelloWorldButton";

export default {
  bootstrap(app) {
    app.injectContentManagerComponent("listView", "actions", {
      name: "HelloWorldButton",
      Component: HelloWorldButton,
    });
  },
};

Qui fait ça :

Vous pouvez choisir où placer votre composant grâce aux deux premiers paramètres du injectContentManagerComponent:

Cet exemple d'injection peut sembler un peu inutile alors je souhaite vous présenter un cas d'utilisation dans lequel je l'ai utilisé.

Dans mon cas, j'ai une page d'accueil qui met en avant certains articles. Ces articles sont choisis par mes rédacteurs grâce à une relation avec ma collection « Article ».

Je ne veux voir dans ma page d'accueil que les articles qui sont publiés et non ceux qui sont rédigés. Malheureusement, le sélecteur utilisé pour faire la relation avec la collection « Article » permet aux utilisateurs de choisir entre tous les articles (même ceux rédigés). Mes rédacteurs pensent que cela peut être dangereux car même s'il y a un petit point de couleur indiquant qu'il n'est pas encore publié, il est possible qu'un jour quelqu'un se trompe et mette en page d'accueil un brouillon d'article.

Dans mon projet, j'ai créé un composant qui utilise le sélecteur natif de Strapi mais j'ai ajouté une coche afin de permettre à l'utilisateur de ne sélectionner que les articles publiés.

NB : Vous pouvez également utiliser cette méthode pour injecter un composant d'un plugin spécifique dans un autre en utilisant la méthodeinjectComponent()qui fonctionne de la même manière queinjectContentManagerComponent()(documentation ici )

Nouveau plugin ?

Si ce que vous voulez faire est plus complexe que des traductions ou ajouter des composants dans l'interface de Strapi, vous devrez probablement créer votre propre plugin. Je vous recommande de lire cet article ou de voir cette vidéo qui sont essentiellement des tutos sur la façon de créer votre propre plugin.

Cette solution est plus complexe et prendra beaucoup plus de temps que les deux autres solutions. Si vous le pouvez, il est préférable d'utiliser la zone d'injection afin de gagner du temps.

Conclusion

Même s'il était globalement plus facile et plus rapide de personnaliser le panneau d'administration de Strapi avec Strapi V3, ce n'était pas très stable. Cette méthode peut être vue comme une éjection de fichier : il s'agit essentiellement de prendre du code de Strapi et de le réécrire dans votre propre base de code, ce qui crée une relation forte entre une bibliothèque externe (Strapi) et votre propre code. A chaque nouvelle version de Strapi si un fichier changeait il fallait aussi changer son code et trouver où le faire et comment le faire. Ce n'était pas très facile à entretenir et cela pouvait casser beaucoup de choses si vous aviez fait beaucoup de modifications.

Dans Strapi V4, il existe toujours une connexion entre Strapi et votre base de code si, par exemple, vous réutilisez le composant de Strapi (comme je l'ai fait dans mon exemple d'injection). Mais la connexion est beaucoup plus petite et vos modifications sont plus stables. Le choix de Strapi pour supprimer la méthode d'éjection semble pragmatique afin de maintenir plus facilement votre application.

Source : https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/

#strapi 

4 Façons De Créer Un Panneau D'administration Strapi Personnalisé
Hoang  Kim

Hoang Kim

1658811600

4 Cách Để Tạo Bảng điều Khiển Quản Trị Strapi Tùy Chỉnh

Vài tháng trước, tôi bắt đầu một dự án với tư cách là kỹ sư phần mềm, trong đó chúng tôi đang sử dụng Strapi V3.

Đối với những người không quen thuộc với Strapi, đây là một CMS (Hệ thống quản lý nội dung) mã nguồn mở, không có đầu cho phép người dùng tạo, quản lý và hiển thị dữ liệu nhờ Bảng quản trị tích hợp sẵn.

Trong dự án của mình, chúng tôi nhanh chóng bắt đầu tùy chỉnh Bảng điều khiển quản trị của Strapi bằng cách ghi đè trực tiếp các tệp trong dự án của mình: chúng tôi chỉ cần tạo lại đường dẫn đến tệp cụ thể mà chúng tôi muốn sửa đổi.

Bạn có thể nghĩ về nó như thể bạn muốn đẩy một tệp cụ thể cần được sửa đổi. Ví dụ: nếu tôi muốn thay đổi màu của nút “Xuất bản / Hủy xuất bản” từ xanh lam sang xanh lục, tôi phải:

  1. Tìm nơi xử lý màu của nút trong kho Github của Strapi V3 . Nó nằm trong tệp: package / strapi-plugin-content-manager / admin / src / container / EditView / Header / index.js . (Đây là tệp tôi muốn đẩy ra)
  2. Tạo thư mục liên quan đến gói trong thư mục tiện ích mở rộng, / extensions / content-manager /
  3. Tạo lại đường dẫn = tạo tệp index.js: extensions / content-manager / admin / src / container / EditView / Header / index.js
  4. Sao chép, dán tệp cũ (từ kho lưu trữ hoặc mô-đun nút)
  5. Thay thế "chính" bằng "thành công" trên dòng 13

Sau đó, khi xây dựng Bảng quản trị Strapi, Strapi sẽ biết rằng tệp này đã được sửa đổi và sẽ sử dụng tệp này thay vì tệp cũ. Và do đó, nút Xuất bản / Hủy xuất bản có màu xanh lục.

Sau đó, Strapi V4 đã được phát hành! Và trong Strapi V4, chức năng này không còn nữa.

Vì vậy, tôi nhanh chóng tự hỏi liệu có còn có thể tùy chỉnh giao diện Strapi của chúng tôi hay không. Trong bài viết này, tôi sẽ trình bày cho bạn bốn cách để tùy chỉnh Bảng quản trị Strapi của bạn, bắt đầu với cách dễ nhất: sử dụng một plugin đã có sẵn. Sau đó, kỹ thuật tùy chọn cấu hình, tiếp theo là phương pháp tệp tiêm, để kết thúc với một kỹ thuật phức tạp hơn: tạo plugin của riêng bạn.

harry potter gif

Để minh họa, tôi đang lấy ví dụ về một phương tiện truyền thông: người viết cần một CMS để viết, chỉnh sửa và xuất bản các bài báo của họ và họ đã chọn Strapi V4.

Plugin hiện có

Điều đầu tiên và dễ dàng nhất cần làm khi bạn muốn tùy chỉnh một thứ gì đó trong giao diện của Strapi là thử và tìm một plugin thực hiện những gì bạn muốn.

Để tìm các plugin, bạn có thể xem:

Trong trường hợp của tôi, các biên tập viên không phải là người hâm mộ lớn của cú pháp đánh dấu được sử dụng trong Đối tượng RichText của Strapi V4, họ sẽ đánh giá cao thứ gì đó thực tế hơn để xem trực tiếp kết quả mà không cần phải sử dụng chế độ xem trước.

Tôi đã tìm thấy plugin "strapi-plugin-editorjs" là một plugin EditorJS dành cho Strapi để thay thế trường RichText do Strapi cung cấp. Tài liệu hướng dẫn rất rõ ràng về cách cài đặt và sử dụng plugin.

Điều duy nhất cần làm trong trường hợp này là:

yarn add strapi-plugin-react-editorjs

Và sau đó, đối tượng RichText trong Bảng điều khiển quản trị Strapi sử dụng EditorJS một:

Điều gì xảy ra nếu plugin tôi muốn không tồn tại?

Tùy chọn cấu hình

Đầu tiên, bạn có thể rất dễ dàng sửa đổi Bảng quản trị Strapi nhờ các tùy chọn cấu hình: tùy chọn này được sử dụng cho các bản dịch, biểu trưng, ​​biểu tượng yêu thích, các ngôn ngữ có sẵn, chủ đề, hướng dẫn và thậm chí cả thông báo (xem tài liệu tại đây ).

Tôi sẽ nhanh chóng chỉ cho bạn cách sử dụng nó với tệp bản dịch và cách thay đổi tất cả các từ ngữ trong giao diện Strapi của bạn.

Bạn phải tìm bản dịch mà bạn muốn thay đổi: ví dụ: nếu tôi muốn thay đổi tiêu đề của trang chủ từ "Chào mừng 👋" thành "Xin chào Chloé!":

💡 Để dễ dàng tìm thấy tệp bản dịch trong thư mục github: bạn có thể thay thế .combằng .devtrong URL Github mở tab VisualStudio trong tab internet của bạn. Và sau đó, tìm trực tiếp bản dịch để thay đổi nhờ tin nhắn cũ 💡

// src/admin/app.js

export default {
  config: {
    translations: {
      en: {
        "app.components.HomePage.welcome.again": "Hi Chloé!",
      },
    },
  },
  bootstrap() {},
};

Bạn sẽ thấy:

💡Sử dụng yarn develop —watch-adminđể xem trực tiếp các sửa đổi bạn đang áp dụng mà không cần phải khởi chạy lại máy chủ của bạn. 💡

Vùng tiêm

Cũng có thể tùy chỉnh Bảng điều khiển quản trị bằng cách sử dụng API vùng tiêm mà không cần phải tạo một plugin với injectContentManagerComponent.

Tôi sẽ lấy một ví dụ đơn giản để cho bạn thấy dễ dàng cách thêm một thành phần tùy chỉnh vào giao diện Strapi của bạn: Tôi muốn thêm một nút trên giao diện của Strapi đang in “Hello World”

Đầu tiên hãy tạo /extensionsthư mục trong src/adminvà sau đó bạn có thể tạo thành phần của mình:

// src/admin/extensions/components/HelloWorldButton/index.js

import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";

const HelloWorldButton = () => {
  return (
    <Button
      variant="secondary"
      startIcon={<Up />}
      onClick={() => alert("Hello World")}
    >
      Hello World
    </Button>
  );
};

export default HelloWorldButton;

Và sau đó sử dụng injectContentManagerComponenttrong tệp app.js để đưa thành phần mới của bạn trực tiếp vào ứng dụng của bạn:

// src/admin/app.js

import HelloWorldButton from "./extensions/components/HelloWorldButton";

export default {
  bootstrap(app) {
    app.injectContentManagerComponent("listView", "actions", {
      name: "HelloWorldButton",
      Component: HelloWorldButton,
    });
  },
};

Mà đang làm điều đó:

Bạn có thể chọn nơi đặt thành phần của mình nhờ vào hai tham số đầu tiên của injectContentManagerComponent:

Ví dụ về tiêm này có vẻ hơi vô dụng vì vậy tôi muốn giới thiệu cho bạn một trường hợp sử dụng mà tôi đã sử dụng nó.

Trong trường hợp của tôi, tôi có một trang chủ làm nổi bật một số bài báo. Những bài báo này được chọn bởi các biên tập viên của tôi nhờ vào mối quan hệ với bộ sưu tập "Bài báo" của tôi.

Tôi chỉ muốn xem trên trang chủ của mình những bài báo đã được xuất bản chứ không phải những bài được soạn thảo. Thật không may, bộ chọn được sử dụng để thực hiện mối quan hệ với bộ sưu tập “Bài báo” cho phép người dùng lựa chọn giữa tất cả các bài báo (ngay cả những bài đã soạn thảo). Người viết của tôi nghĩ rằng nó có thể nguy hiểm vì ngay cả khi có một chút điểm màu cho thấy nó chưa được xuất bản, có thể một ngày nào đó ai đó làm sai và đưa lên trang chủ một bài báo nháp.

Trong dự án của mình, tôi đã tạo một thành phần sử dụng bộ chọn gốc của Strapi nhưng tôi đã thêm dấu kiểm để cho phép người dùng chỉ chọn các bài báo đã xuất bản.

NB: Bạn cũng có thể sử dụng phương pháp này để đưa một thành phần của một plugin cụ thể vào một plugin khác bằng cách sử dụng phương phápinjectComponent()hoạt động giống nhưinjectContentManagerComponent()(tài liệu ở đây )

Plugin mới?

Nếu những gì bạn muốn làm phức tạp hơn là dịch hoặc thêm các thành phần vào giao diện của Strapi, bạn có thể sẽ phải tạo plugin của riêng mình. Tôi khuyến cáo bạn đọc bài viết này hoặc xem video này về cơ bản hướng dẫn cách tạo plugin của riêng bạn.

Giải pháp này phức tạp hơn và sẽ mất nhiều thời gian hơn so với hai giải pháp còn lại. Nếu bạn có thể, tốt hơn là sử dụng vùng tiêm để tiết kiệm thời gian.

Sự kết luận

Ngay cả khi việc tùy chỉnh Bảng quản trị Strapi bằng Strapi V3 dễ dàng và nhanh chóng hơn trên toàn cầu, nó vẫn không ổn định lắm. Phương pháp này có thể được coi là một loại bỏ tệp: về cơ bản nó là lấy một số mã từ Strapi và viết lại nó trong cơ sở mã của riêng bạn, điều này tạo ra mối quan hệ chặt chẽ giữa thư viện bên ngoài (Strapi) và mã của riêng bạn. Tại mỗi phiên bản mới của Strapi, nếu một tệp thay đổi, bạn cũng phải thay đổi mã của mình và tìm nơi thực hiện và cách thực hiện. Nó không thể bảo trì được và nó có thể làm hỏng rất nhiều thứ nếu bạn đã thực hiện nhiều sửa đổi.

Trong Strapi V4, vẫn có một kết nối giữa Strapi và cơ sở mã của bạn, ví dụ: nếu bạn đang sử dụng lại thành phần của Strapi (như tôi đã làm trong ví dụ tiêm của mình). Nhưng kết nối nhỏ hơn nhiều và các sửa đổi của bạn ổn định hơn. Việc lựa chọn Strapi để loại bỏ phương pháp đẩy có vẻ thực dụng để duy trì ứng dụng của bạn dễ dàng hơn.

Nguồn: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/

#strapi 

4 Cách Để Tạo Bảng điều Khiển Quản Trị Strapi Tùy Chỉnh
郝 玉华

郝 玉华

1658811600

构建自定义 Strapi 管理面板的 4 种方法

几个月前,我作为一名软件工程师开始了一个项目,我们在其中使用了 Strapi V3。

对于那些不熟悉 Strapi 的人来说,它是一个开源的无头 CMS(内容管理系统),借助内置的管理面板,它允许用户创建、管理和公开数据。

在我的项目中,我们很快开始通过直接覆盖项目中的文件来自定义 Strapi 的管理面板:我们只需要重现我们想要修改的特定文件的路径。

你可以把它想象成你想弹出一个需要修改的特定文件。例如,如果我想将“发布/取消发布”按钮的颜色从蓝色更改为绿色,我必须:

  1. 在Strapi V3的 Github 存储库中查找按钮颜色的处理位置。它在文件中:packages/strapi-plugin-content-manager/admin/src/containers/EditView/Header/index.js。(这是我要弹出的文件)
  2. 在扩展文件夹/extensions/content-manager/中创建相对于包的文件夹
  3. 重新创建路径 = 创建 index.js 文件:extensions/content-manager/admin/src/containers/EditView/Header/index.js
  4. 复制粘贴旧文件(来自存储库或节点模块)
  5. 在第 13 行将“primary”替换为“success”

然后,在构建 Strapi 管理面板时,Strapi 会知道该文件已被修改,并将使用该文件而不是旧文件。因此,发布/取消发布按钮是绿色的。

然后 Strapi V4 上线了!而在 Strapi V4 中,此功能不再可用。

所以我很快想知道是否仍然可以自定义我们的 Strapi 界面。在本文中,我将向您介绍四种自定义 Strapi 管理面板的方法,从最简单的一种开始:使用现有的插件。然后是配置选项技术,然后是注入文件方法,以完成更复杂的方法:创建您自己的插件。

哈利波特.gif

为了说明,我以媒体为例:作者需要一个 CMS 来编写、编辑和发布他们的文章,他们选择了 Strapi V4。

现有插件

当您想在 Strapi 的界面中自定义某些内容时,要做的第一件事也是最简单的事情是尝试找到一个可以满足您需求的插件。

要查找插件,您可以查看:

在我的例子中,编辑们不是 Strapi V4 的 RichText 对象中使用的 markdown 语法的忠实拥护者,他们会欣赏更真实的东西,直接看到结果而不必使用预览模式。

我找到了插件“strapi-plugin-editorjs”,这是一个用于 Strapi 的 EditorJS 插件,用于替换 Strapi 提供的 RichText 字段。文档非常清楚如何安装和使用该插件。

在这种情况下唯一要做的是:

yarn add strapi-plugin-react-editorjs

在此之后,Strapi 管理面板中的 RichText 对象使用 EditorJS 之一:

如果我想要的插件不存在怎么办?

配置选项

首先,由于配置选项,您可以非常轻松地修改 Strapi 管理面板:这用于翻译、徽标、网站图标、可用的语言环境、主题、教程甚至通知(请参阅此处的文档)。

我将快速向您展示如何将它与翻译文件一起使用以及如何更改 Strapi 界面的所有措辞。

您必须找到要更改的翻译:例如,如果我想将主页的标题从“Welcome 👋”更改为“Hi Chloé!”:

💡 要在 github 文件夹中轻松找到翻译文件:您可以替换Github URL.com中的by .dev,这会在您的 Internet 选项卡中打开一个 VisualStudio 选项卡。然后直接找翻译改感谢老留言💡

// src/admin/app.js

export default {
  config: {
    translations: {
      en: {
        "app.components.HomePage.welcome.again": "Hi Chloé!",
      },
    },
  },
  bootstrap() {},
};

你会看见:

💡yarn develop —watch-admin用于直接查看您正在应用的修改,而无需重新启动您的服务器。💡

注射区

也可以使用注入区 API 自定义管理面板,而无需使用injectContentManagerComponent.

我将举一个简单的例子来轻松地向您展示如何在 Strapi 的界面中添加自定义组件:我想在 Strapi 的界面上添加一个打印“Hello World”的按钮

首先在其中创建/extensions文件夹,src/admin然后您可以创建组件:

// src/admin/extensions/components/HelloWorldButton/index.js

import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";

const HelloWorldButton = () => {
  return (
    <Button
      variant="secondary"
      startIcon={<Up />}
      onClick={() => alert("Hello World")}
    >
      Hello World
    </Button>
  );
};

export default HelloWorldButton;

然后使用injectContentManagerComponentapp.js 文件中的 将新组件直接注入到您的应用中:

// src/admin/app.js

import HelloWorldButton from "./extensions/components/HelloWorldButton";

export default {
  bootstrap(app) {
    app.injectContentManagerComponent("listView", "actions", {
      name: "HelloWorldButton",
      Component: HelloWorldButton,
    });
  },
};

这是这样做的:

由于 的前两个参数,您可以选择放置组件的位置injectContentManagerComponent

这个注入示例可能看起来有点无用,所以我想向您展示一个我使用它的用例。

就我而言,我有一个主页,其中突出显示了一些文章。这些文章是由我的编辑选择的,这要归功于与我的“文章”收藏的关系。

我只想在我的主页上看到已发布的文章,而不是草稿的文章。不幸的是,用于与“文章”集合建立关系的选择器允许用户在所有文章(甚至是草稿)之间进行选择。我的作者认为这可能很危险,因为即使有一点点颜色表明它还没有发表,也有可能有一天有人犯了错误并在主页上放了一篇文章草稿。

在我的项目中,我创建了一个使用 Strapi 的本机选择器的组件,但我添加了一个检查以允许用户仅选择已发布的文章。

注意:您也可以使用此方法将特定插件的组件注入另一个插件,方法injectComponent()(此处injectContentManagerComponent()的文档)

新插件?

如果您想要做的比翻译更复杂或在 Strapi 的界面中添加组件,您可能必须创建自己的插件。我建议你阅读这篇文章或观看这个视频,这些视频基本上是关于如何创建自己的插件的教程。

这个解决方案比其他两个解决方案更复杂,并且需要更多的时间。如果可以,最好使用注射区以节省一些时间。

结论

即使使用 Strapi V3 自定义 Strapi 管理面板在全球范围内更容易、更快捷,它也不是很稳定。这种方法可以看作是文件弹出:它基本上是从 Strapi 中获取一些代码并在您自己的代码库中重写它,这在外部库(Strapi)和您自己的代码之间建立了牢固的关系。在 Strapi 的每个新版本中,如果文件发生更改,您还必须更改代码并找到在哪里执行以及如何执行。它不是很容易维护,如果你做了很多修改,它可能会破坏很多东西。

在 Strapi V4 中,Strapi 和您的代码库之间仍然存在连接,例如,如果您正在重用 Strapi 的组件(就像我在注入示例中所做的那样)。但是连接要小得多,您的修改更稳定。选择 Strapi 删除弹出方法似乎很实用,以便更轻松地维护您的应用程序。

来源:https ://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/

#strapi 

构建自定义 Strapi 管理面板的 4 种方法

4 Ways to Build A Custom Strapi Admin Panel

Few months ago, I started a project as a software engineer in which we were using Strapi V3.

For those who are not familiar with Strapi, it is an open-source, headless CMS (Content Management System) which allows users to create, manage and expose data thanks to a built-in Admin Panel.

On my project, we quickly began to customize the Strapi’s Admin Panel by directly overriding the files in our project: we just had to reproduce the path to the specific file we wanted to modify.

You can think of it as if you wanted to eject a specific file which needs to be modified. For example, if I want to change the color of a the “Publish/Unpublish” button from blue to green, I have to:

See more at: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/

#strapi 

4 Ways to Build A Custom Strapi Admin Panel