什麼是 React?

React 是一個 JS 的函式庫,Gatsby 用它來創造 UI,好處是可以把 UI 切成一個一個可以 重複利用 的 components

React Component?

是一個函式會 return React element,而 React element 是一個物件 React 用來渲染 DOM

示意圖
react-component-img

React Component 的重要元素

  1. Import React from the react package, so that you can use JSX inside your .js file.
  2. Define your component. It should be a function that returns a JSX element.
  3. Export your component, so that it can be used by other parts of your site.

重複出現的 component

src/components 底下創一個 layout.js 檔案,讓 components 可以共用

component with children 範例 code
  • src/components/layout.js
component-layout
  • src/pages/index.js
react-index

GraphQL 拿資料

用 Gatsby - GraphiQL (localhost:8000/__graphql) 試跑指令,確保 result data 是自己要的

流程示意圖
  • source → data layer → components
graphql image
取得資料步驟
  1. Add a source plugin to add data into the GraphQL data layer.
  2. Use GraphiQL to design a query that responds with the data you want from the data layer.
  3. Add the query into your component.
    • Use page queries for page components.
    • Use useStaticQuery for “building block” components.
  4. Use the data from the response in your component.

Transform data to use MDX

MDX : 是一個融合了 MarkDown 與 JSX 的格式。可以用 JSX (javascript extension) 到 markdown content,可以 import components, 像是互動式表格,如下面例子

mdx image

File System Route API

  • 在 Gatsby,我們把每個網站寫在 src/pages 底下,但當我們想要每一項產品都有自己的頁面,我們總不能一直重複地把每一項產品的網頁寫在 src/pages 底下吧,因此,我們可以利用 Route API
  • Route API 會動態的新增 page 在 src/pages 底下
Slug

a unique identifier for the resource

Route API 示意圖
routeAPI image