Try   HackMD

From Zero to know what React is


how to create React app ?

  1. 去你想add file 既目標路徑

Create Project

用Vite黎start your project
Vite

npm create vite@latest

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

  1. React

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

  1. TypeScript + SWC

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

  1. npm install
  2. npm run dev

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

  • name can no longer contain capital

搞掂

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

terminal有suggest你run 乜野command,留心睇

見到呢頁代表OK

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

  1. App.css , 入面既野all delete
  2. index.css, 入面既野all delete
  3. App.tsx ,<>empty tag 入面既野alldelete

Before delete

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

After delete - delete< div > 轉 < >

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

main.tsx入面包住App.tsx
App.tsx return 出去,return去邊度?
main.tsx -> 入面render緊app既野

Define component :
function_Component_Example:

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

class_Component_Example :

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →


when we call API in React will have 5 steps :

  1. Construct the UI with fake data
  2. Download the JSON file and import as a mockData.
  3. Construct the data ts file with "export interface".
  4. Add the mock data to UI.
  5. Use axios to call the API and add the response data to the UI.

React JS Roadmap

Foundation

The First Step

create-react-app

Components

Functional_Components

JSX

Props_&_State

Hooks:useState,useEffect

Conditional_Rendering

List_Keys

Events_Input_Handling


The React Ecosystem

Routing

React_Router

State_Management

Styling

HTTP

Forms

Context_API

Redux

Styled_Components

Tailwind_CSS

Using_Fetch_In_React

Axios

Hook_Form_Handling

Formik


The Advanced Topics

useRef , useMemo,useCallback...

Refs

Higher_Order_Components

Error_Boundaries

Practice


HTML
  • 介紹 HTML
    • HTML 代表HyperText Markup Language(超文本標記語言),用黎創建同設計網頁既標記語言。
  • HTML 基本結構
    • HTML 基本Format:
      ​​​​<!DOCTYPE html>
      ​​​​<html>
      ​​​​  <head>
      ​​​​    <title>Page Title</title>
      ​​​​  </head>
      ​​​​  <body>
      ​​​​    <h1>This is a Heading</h1>
      ​​​​    <p>This is a paragraph.</p>
      ​​​​  </body>
      ​​​​</html>
      
  • 常見 HTML 標籤和屬性
    • 常見 HTML 標籤:<div>, <p>, <h1>, <a>, <img>, <ul>, <ol>, <li>, <table>, <form>, 等。
    • HTML 標籤屬性:例如 src(圖片的來源)、href(超鏈接的目的地)、alt(圖片的替代文本)等。
  • HTML CheatSheet
CSS
  • CSS 是什麼?

    • CSS 意為層疊樣式表,用於定義網頁的外觀和樣式,與 HTML 一同使用。
  • CSS 選擇器和屬性

    • CSS 選擇器:選擇器用於選擇要樣式化的 HTML 元素,如 .class#id、元素名稱等。
    • CSS 屬性:例如 color(文字顏色)、font-size(字體大小)、margin(外邊距)等。
  • 布局和盒模型

    • CSS 布局:常見的布局方法,包括流式布局、浮動、彈性布局等。
    • 盒模型:元素由內容、內邊距、邊框和外邊距組成。
  • Flexbox 和 Grid 布局

  • 媒體查詢 (Media Queries)

    • Media Queries 允許根據設備特性(如視口寬度、裝置類型)應用不同的樣式。

    • 作用: 主要用於實現響應式網頁設計,使網頁能夠適應不同的裝置和屏幕大小,提供更好的使用體驗。

    • Media Queries 的基本語法

      ​​​​@media Media_Type and (條件) {
      ​​​​ /* 應用於符合條件的樣式 */
      ​​​​}
      

      常見的Media_Type
      all: 所有Media_Type。
      print: 打印機和打印預覽。
      screen: 顯示器屏幕。
      speech: 螢幕閱讀器等發聲設備。

    • 範例:

      ​​​​  @media screen and (min-width: 768px) and (max-width: 1200px) {
      ​​​​  /* 寬度在 768px 到 1200px 之間時應用的樣式 */
      ​​​​    }
      
      ​​​​@media screen and (orientation: portrait) {
      ​​​​  /* 縱向時應用的樣式 */
      ​​​​}
      
  • 響應式圖像

    • max-width: 100% 保證圖片在不拉伸尺寸的情況下保持適應屏幕大小。
    • srcset 屬性提供不同解析度的圖像,讓瀏覽器根據需要選擇。
  • Flexbox 和 Grid 既High-level Usage

    • 進階的 Flexbox 佈局:運用 flex-growflex-shrinkflex-basis 等屬性進行更細緻的佈局。
    • Grid 布局進階技巧:使用 grid-template-areasgrid-gapgrid-template-columns 等進階屬性。
JS
  • JavaScript 係乜?

    • JavaScript 是一種動態、直譯的程式語言,用於使網頁交互,實現動態效果。
    • JavaScript
  • 變量、數據類型和運算符

    • varletconst 變數聲明的不同方式。
      • var唔用,用let取代
      • const 常數
    • 基本數據類型:Number、String、Boolean、Null、Undefined、Array、Object。
    • 運算符:算術、比較、邏輯運算符等。
  • 條件語句和迴圈

    • ifelse
    • forwhile
  • 函數和事件處理

    • 函數的定義和呼叫:重用程式碼的方法。
    • 事件處理:應對使用者互動的方式。
  • DOM 簡介

    • DOM 是文檔物件模型,通過 JavaScript 與 HTML 文檔互動的接口。
    • JS Event & DOM
  • 選擇元素和修改內容

    • getElementByIdgetElementsByClassNamequerySelector 等方法選擇 DOM Elements。
    • 修改元素內容:使用 innerHTMLinnerText 等屬性。
  • 創建和刪除元素

    • createElementappendChild:動態創建和添加元素。
    • removeChild:刪除元素。
  • 事件處理進階

    • 事件冒泡和捕獲:理解事件傳播的不同階段。
    • 事件委託:提高事件效能的技巧。

JS Cheat Sheet

Basic Things To Learn

Components

Passing Props to a Component , 所有Component大階開頭

Props 係一個parameter , 用object形式放落 component

functional component -> 依家call一個function,可以比args,比parameter->
parent比野child -> 呢樣就叫props

但child return JSX出去,比main做Rendering

props can be objects,arrays,functions

Class Component

classComponentExample

Function Component

其他cap圖全部以Function Component做

functionComponentExample

JSX (JavaScript XML)
  • JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JS file.想一次過係JS file寫晒 html,jsx幫你create element

for each 無野return,行完就算

React {} => 代表你想係JSX入面寫JS ->Curly Braces

  • outer {} => 我要寫JS
  • inner{} => JS Object

JSX Rules:

1 Return 入面一定係 single root element
2.single tag 要有 '/'變尾 -> <img />
3.駝峰命名
4.想係JSX入面寫JS加 '{}'
tips : 善用好用conventer網轉換JSX,JS,TS 好用conventer網

JavaScript in JSX with Curly Braces

螢幕截圖 2023-12-10 下午5.36.41
螢幕截圖 2023-12-10 下午5.36.52

TSX (TypeScript XML)

螢幕截圖 2023-12-10 下午5.40.40
螢幕截圖 2023-12-10 下午5.40.46

Props

Props:
功能: Props 是 read-only component , object , 用黎store Attributes,是由father component傳遞給child component的數據。它是Read only,child component不能直接修改 props。
作用: 允許father component向child component傳遞數據,從而使component之間connect。
舉例:

// Parent Component const ParentComponent = () => { const message = "Hello from Parent!"; return <ChildComponent message={message} />; }; // Child Component const ChildComponent = (props) => { return <div>{props.message}</div>; };
State

功能: State 是==variable==,它用於跟蹤隨時間而變化既data。與 props 不同,state 是可變的,可以通過調用setState 來更新。
作用: 用於在組件中保存和管理局部狀態,以實現動態 UI 和響應用戶操作。
舉例:

// Component with State class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0, }; } incrementCount = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.incrementCount}>Increment</button> </div> ); } }
Events

onClick

onClick

Conditional Rendering
  1. 另外開method 做

conditionRendering1:4

  1. 直接係Component做if-else , 得一個Component比較適合

    conditionRendering2:4

  2. return 入面用 ? :

    conditionRendering3:4

  3. 用 && || (小用||)

    conditionRendering4:4

{}入面只能夠放一句expression :想做if statements用 &&, and ? :

Rendering Lists

每次retrun一個single root element,所以要分開包住

整component->Reuseable

整component->Reuseable

Rendering分兩種

伺服器端渲染(Server-Side Rendering,SSR)

伺服器端渲染 (SSR):

由server行晒全部JS,砌好晒HTML,再掉比電腦,每load一頁,轉部page,問server拎部HTML,每一下都load耐D
ADV: security高 ,call api動作係server做晒,砌好成個html再掉比你:銀行系統
NextJS包住ReactJS,所以行到SSR->寫法唔同

  • 執行地點:
    渲染發生在伺服器上。
  • 流程:
    當用戶請求頁面時,伺服器生成 HTML,包含所有必需的資料和內容。
    完整的 HTML 內容被直接發送到瀏覽器。
  • 優點:
    更快的首次載入時間,因為用戶接收到完整的頁面。
    更好的 SEO(搜尋引擎優化)效果,因為搜索引擎能夠直接解析 HTML 內容。
  • 缺點:
    較大的首次載入時間,因為整個頁面的內容都需要在伺服器端生成。
    對伺服器的較大負載,特別是在高流量的情況下。
  • 適用情境:
    需要 SEO 優化的內容網站。
    初始頁面載入速度較為重要的情況。
    • Next.js (React 框架的 SSR 擴展):
      安裝:npm install next

    • Nuxt.js (Vue.js 框架的 SSR 擴展):
      安裝:npm install nuxt

    • Angular Universal:
      安裝:ng add @nguniversal/express-engine

客戶端渲染(Client-Side Rendering,CSR)

客戶端渲染 (CSR):

做一個Single page application,係將成個JS download 落電腦,由JS去控制介面有D乜。start 個下loading 最耐,唔用network時間run
電腦call api,比人睇晒:銀行call api唔想比人知
最raw react 一定做CSR

  • 執行地點:
    渲染發生在用戶的瀏覽器中。
  • 流程:
    瀏覽器接收到最小的 HTML 內容,通常僅包含基本的結構和載入 JavaScript 的標籤。
    瀏覽器下載 JavaScript 並在用戶的設備上運行,以動態生成和更新頁面內容。
  • 優點:
    快速的初始載入時間,因為僅傳送最小的 HTML 內容。
    渲染過程可以在用戶設備上進行,減輕伺服器負擔。
  • 缺點:
    可能有較差的 SEO 效果,因為搜索引擎在初始載入時看到的僅是基本 HTML 結構。
    首次載入後,需要進行額外的資源請求和渲染,可能導致較慢的用戶體驗。
  • 適用情境:
    需要動態更新和即時互動的應用程式。
    對初始載入時間較不敏感的情況,例如單頁應用(Single Page Application)。
    • React:
      使用 create-react-app 快速啟動 React 專案,預設支援 CSR。
    • Vue.js:
      使用 Vue CLI 快速啟動 Vue 專案,預設支援 CSR。
    • Angular:
      使用 Angular CLI 快速啟動 Angular 專案,預設支援 CSR。

Learn Important Hooks

React 生命周期

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

useState
  • React 內建StateObject
  • 屬於某個特定Component資料
  • React 對State變化有反應(Reactive to State)
  • 更新component(re-render)即時睇到變化
    useState例子
useEffect
  • useEffect 用於處理副作用操作,如數據獲取(fetch data)、訂閱等。它在每次render之後運行。
    useEffect例子1

    useEffect例子2

    useEffect 例子3
useRef

useRef解釋

  • useRef返回一个可變的ref對象
import React, { useRef, useEffect } from 'react'; const RefComponent = () => { const inputRef = useRef(); useEffect(() => { inputRef.current.focus(); // 獲取焦點 }, []); return <input ref={inputRef} />; };
useContext
  • useContext 用於在 React tree中傳遞當前上下文的值。(通常是 React.createContext 的返回值),並返回當前上下文的值。
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <p>Current Theme: {theme}</p>; };
useReducer
  • useReducer 用於管理複雜狀態邏輯,類似於 useState,但提供更多控制。
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; default: return state; } }; const ReducerComponent = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> </div> ); };
useMemo
  • useMemo 用於根據依賴值的變化,計算記憶化值用於緩存計算結果,以節省計算資源。
import React, { useMemo } from 'react'; const MemoizedComponent = ({ list }) => { const sortedList = useMemo(() => list.sort(), [list]); return <ul>{sortedList.map((item) => <li key={item}>{item}</li>)}</ul>; };
useCallback
  • useCallback 用於緩存回調函數,以防止不必要的重新創建。
import React, { useCallback, useState } from 'react'; const CallbackComponent = () => { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount(count + 1); }, [count]); return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); };

Learn Some Of The React UI Frameworks

  • React Router
  • React Query
Axios
Feature Axios Fetch API
Easy of Use Simple aPI , automatic JSON parsing Lower-level API , manual response parsing
Interceptors Yes,built-in support No,requires manual handling
Browser Compatibility Browsers and Node.js Native browers feature , requires polyfills
Size Slightly larger Smaller (native brower functionality)
Error Handling Automatic JSON parsing Requires explicit parsing (e.g. 'response.json()')
Community & Maintenace Actively maintained , strong community Part of native brower API , maintained by browser vendors

Axios Installation

//Using NPM

npm install axios

// Using Yarn

yarn add axios

Marking GET Request

import axios from 'axios'; axios.get('URL') .then(response=>{ console.log(response.data); }) .catch(error=>{ console.error(error); });

Marking POST Request

import axios from 'axios'; //Define headers const headers = { 'Content-Type':'application/json', 'Authorization':'Bearer YOUR_ACCESS_TOKEN' }; //Define data to send in the body const dataToSend = { key1:'value1', key2:'value2', } //Make the axios request axios.post('URL',dataToSend,{headers}) .then(response=>{ console.log(response.data); }) /catch(error=>{ console.error(error); });

Marking PUT Request

import axios from 'axios'; const dataToUpdate = { key1:"value1", key2L"value2 }; axios.put(`http://.../data/${id}`,dataToUpdate) .then(response=>{ console.log(response); }) .catch(error=>{ console.error(error); });

Marking DELETE Request

import axios from 'axios'; axios.delete(`https://data/${id}`) .then((response)=>{ console.log(response); }) .catch((error)=>{ console.error(error); });

Call API in React

JS - Promises (Object)

  • Producing Code
    • 會take times既 -> is code that take some time->
  • Consuming Code
    • 要等有結果 -> is code that must wait for the result -> promise有result

所以:call api 呢個動作係Producing Code

  1. fetch
  2. axios

axios

.then() -> 200先行 .catch() ->3xx,4xx,5xx .finally() 似try-catch

async , await -> 簡化.then() ,一對出現

React 生命周期

Search JS 有咩libary用

  • loading時出現既叫skeleton

mounting -> 準備擺上去既時候
Render phase -> side effect ,影響render時間->幾時要等?->call api
有side effect既野唔想放係
Unmounting -> componentWillUnmount

  1. ForecastData -> convent Api JSON first
  2. 將D野加落去 -> 搞State
fetch (Referenca only)

1.使用 fetch 發送 GET 請求:

import React, { useEffect, useState } from 'react'; const ApiIntegrationExample = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); // Empty dependency array ensures the effect runs once after initial render return ( <div> {data ? ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ) : ( <p>Loading data...</p> )} </div> ); }; export default ApiIntegrationExample;

上述例子中,我們使用 fetch 函數向 https://api.example.com/data 發送 GET 請求,然後解析 JSON 數據並將其存儲在組件的狀態中。當數據獲取完成後,顯示數據列表,否則顯示“Loading data”。

2.使用 fetch 發送 POST 請求:

import React, { useState } from 'react'; const ApiIntegrationExample = () => { const [postData, setPostData] = useState({ name: '', age: '' }); const handlePostRequest = async () => { try { const response = await fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData), }); if (response.ok) { console.log('User added successfully'); } else { console.error('Failed to add user'); } } catch (error) { console.error('Error sending POST request:', error); } }; return ( <div> <h2>Add User</h2> <form> <label> Name: <input type="text" value={postData.name} onChange={e => setPostData({ ...postData, name: e.target.value })} /> </label> <label> Age: <input type="text" value={postData.age} onChange={e => setPostData({ ...postData, age: e.target.value })} /> </label> <button type="button" onClick={handlePostRequest}> Add User </button> </form> </div> ); }; export default ApiIntegrationExample;
  • React Hook Form
  • Styled Components
  • Storybook
  • Framer Motion

Learn How To Manage State In React With State Management

  • Redux
  • MobX
  • Hookstate
  • Recoil
  • Akita

Learn To Test Your Apps With Some OF These Libraries / Frameworks

  • Jest
  • Testing Library
  • Cypress
  • Enzyme
  • Jasmine
  • Mocha

React 係乜?
  • React 係乜?

    • A front-end JS framework by Facebook
    • Modalized things into Components
    • Single page Application
  • React 元件和屬性

    • 元件: React應用程序是由許多小組件構成的。元件是可重用的、独立的、有自己的狀態(state)和生命周期的構建塊。
    • 屬性: React 元件接受屬性(props)作為輸入,這些屬性是從父元件傳遞的數據。屬性是不可變的,它們用於定義元件的外觀和行為。
  • JSX 語法

    • JSX 是一種 JavaScript 的語法擴展,類似 XML/HTML,但在 JavaScript 中使用。
    • 例子:
    ​​ - const element = <h1>Hello, React!</h1>;
  • React 開發工具

  • 組件狀態和屬性

    • 使用 useState 鉤子管理組件內的狀態。
    • 屬性和狀態的異同:何時使用屬性,何時使用狀態。
    • 組件狀態: 每個 React 組件都可以擁有自己的內部狀態,通常用於存儲和管理組件的數據。狀態可由 setState 方法進行更新。
    • 組件屬性: 組件的屬性是由父組件傳遞的數據,它們是組件的配置。屬性是不可變的,組件不能直接修改自己的屬性。
  • 生命週期方法

    • React 組件有生命週期方法,這些方法在組件的不同階段被調用,例如組件的創建、更新和卸載。生命週期的階段:componentDidMountcomponentDidUpdatecomponentWillUnmount 等。
  • React Hooks

    • Hooks 是 React 16.8 中引入的新特性,它允許你在不使用類組件的情況下使用狀態和其他 React 功能。一些常用的 Hooks 包括 useState、useEffect 和 useContext。
  • React 路由

    • React Router 是一個用於處理 React 應用程序中路由的庫。它允許你定義應用程序的不同頁面,並在這些頁面之間進行導航。
  • 資料傳遞和狀態提升

    • 資料傳遞:使用 propscontext 進行組件間的數據傳遞。
    • 狀態提升:提升狀態以實現多個組件之間的同步。
  • API 整合

    • 在 React 應用程序中,你可能需要與外部數據源(如後端 API)進行集成。這通常涉及使用 fetch 或其他 HTTP 請求庫,以獲取和發送數據。

Functional Components

Functional Components

螢幕截圖 2023-12-10 下午5.49.33

Functional Components with Props

螢幕截圖 2023-12-10 下午5.53.17

Map Elements

code

螢幕截圖 2023-12-10 下午5.57.08


寫React唔同Springboot,React無logic,似砌lego,design網頁擺位,煩component:Table / Box / Container / Grid / Tabs / NavBar 每一part component 砌好,再group埋所有component做page,如此類推重重覆覆做,就寫得到

Reference Project - Shopping Cart
Github repo : Shopping Cart


Preflight response is not successful. Status code: 401

Preflight_response_is_not_successful_Status_code_401

解決方法:

step 1.Springboot Controller add

@CrossOrigin(origins = "http://localhost:xxxx", maxAge = 3600) => xxxx is your port in React

step 2.SecurityConfig add

.cors(Customizer.withDefaults());

Customizer_withDefaults


git clone 完run 唔到project:

1. rm -rf node_modules 2. rm package-lock.json 3. npm install

DDOS 自己

DDOS_myself

DDOS_detail1

DDOS_detail2


Extra :

用python 拎到人地個網既design:

python_web_scrap


Made by Oscar