kiến thức React cho người mới bắt đầu: Cách tạo một ứng dụng từ a-z

Bạn nào thích học Front-End thì inbox mình nhé.
Mình dạy miễn phí, 7h30 tối mỗi ngày, 30 phút / buổi.

Một số điểm mà mình sẽ cover:
  1. HTML, CSS, JavaScript cơ bản và nâng cao
  2. Mindset về trải nghiệm và giao diện người dùng UX UI
  3. Version control
  4. React cơ bản và nâng cao
  5. Kinh nghiệm phỏng vấn, algorithms, và computer science
  6. Một chút ít về Product Management và Agile
Lớp học qua discord, cần các bạn có internet ổn định, camera và microphone. Khi code và fix bug sẽ chia sẻ màn hình để mọi người tham khảo.
bác ơi em muốn học ạ
 
Bạn nào thích học Front-End thì inbox mình nhé.
Mình dạy miễn phí, 7h30 tối mỗi ngày, 30 phút / buổi.

Một số điểm mà mình sẽ cover:
  1. HTML, CSS, JavaScript cơ bản và nâng cao
  2. Mindset về trải nghiệm và giao diện người dùng UX UI
  3. Version control
  4. React cơ bản và nâng cao
  5. Kinh nghiệm phỏng vấn, algorithms, và computer science
  6. Một chút ít về Product Management và Agile
Lớp học qua discord, cần các bạn có internet ổn định, camera và microphone. Khi code và fix bug sẽ chia sẻ màn hình để mọi người tham khảo.
how to join bác nhỉ
 
Bạn nào thích học Front-End thì inbox mình nhé.
Mình dạy miễn phí, 7h30 tối mỗi ngày, 30 phút / buổi.

Một số điểm mà mình sẽ cover:
  1. HTML, CSS, JavaScript cơ bản và nâng cao
  2. Mindset về trải nghiệm và giao diện người dùng UX UI
  3. Version control
  4. React cơ bản và nâng cao
  5. Kinh nghiệm phỏng vấn, algorithms, và computer science
  6. Một chút ít về Product Management và Agile
Lớp học qua discord, cần các bạn có internet ổn định, camera và microphone. Khi code và fix bug sẽ chia sẻ màn hình để mọi người tham khảo.
mình tham gia rồi, chủ thớt nhớ giữ đều phong độ nhé :beauty:
 
Có 2 cách để import và export components
  • Default
  • Named
For example
JSX:
function Profile() {
  return (
    <img
      src="https://i.imgur.com/MK3eW3As.jpg"
      alt="Katherine Johnson"
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

Ở phía trên, mình có một component <Profile /> sử dụng nội bộ trong file. Parent component là <Gallery />, sử dụng keyword là export default, nghĩa là xuất ra mặc định.

Trong 1 file chỉ có 1 export default, và export cách nào thì import cách đó. Ví dụ

JSX:
import Gallery from './Gallery.js';

export default function App() {
  return (
    <Gallery />
  );
}

Trong file này, mình nhập vào component là <Gallery />, đã được xuất ra trước đó.

Trong 1 file, chỉ có 1 export default component, nhưng có thể có nhiều export named component. Ví dụ

JSX:
export function Button() {
    // ...
}

export function Submit() {
    // ...
}

export default function Gallery() {
    // ...
}

Sau đó, để import 2 named export components là <Button /> và <Submit />, ta dùng keyword
JSX:
import {Button, Submit} from './gallery';

// ...
 
Hôm nay, chúng ta sẽ làm về một phần UI đơn giản như sau
  • Có 3 nút (buttons) để xem ảnh tiếp theo (next), xem ảnh trước (previous), và để xem mô tả (show more)
  • Có một dòng heading để thể hiện tên tác giả - tác phẩm
  • Có một hình ảnh
UI.png


Đầu tiên, cần lưu dữ liệu trong một file riêng biệt, tên là file.js

JSX:
export const sculptureList = [{
  name: 'Homenaje a la Neurocirugía',
  artist: 'Marta Colvin Andrade',
  description: 'Although Colvin is predominantly known for abstract themes that allude to pre-Hispanic symbols, this gigantic sculpture, an homage to neurosurgery, is one of her most recognizable public art pieces.',
  url: 'https://i.imgur.com/Mx7dA2Y.jpg',
  alt: 'A bronze statue of two crossed hands delicately holding a human brain in their fingertips.'
}, {
  name: 'Floralis Genérica',
  artist: 'Eduardo Catalano',
  description: 'This enormous (75 ft. or 23m) silver flower is located in Buenos Aires. It is designed to move, closing its petals in the evening or when strong winds blow and opening them in the morning.',
  url: 'https://i.imgur.com/ZF6s192m.jpg',
  alt: 'A gigantic metallic flower sculpture with reflective mirror-like petals and strong stamens.'
}, {
  name: 'Eternal Presence',
  artist: 'John Woodrow Wilson',
  description: 'Wilson was known for his preoccupation with equality, social justice, as well as the essential and spiritual qualities of humankind. This massive (7ft. or 2,13m) bronze represents what he described as "a symbolic Black presence infused with a sense of universal humanity."',
  url: 'https://i.imgur.com/aTtVpES.jpg',
  alt: 'The sculpture depicting a human head seems ever-present and solemn. It radiates calm and serenity.'
}, {
  name: 'Moai',
  artist: 'Unknown Artist',
  description: 'Located on the Easter Island, there are 1,000 moai, or extant monumental statues, created by the early Rapa Nui people, which some believe represented deified ancestors.',
  url: 'https://i.imgur.com/RCwLEoQm.jpg',
  alt: 'Three monumental stone busts with the heads that are disproportionately large with somber faces.'
}, {
  name: 'Blue Nana',
  artist: 'Niki de Saint Phalle',
  description: 'The Nanas are triumphant creatures, symbols of femininity and maternity. Initially, Saint Phalle used fabric and found objects for the Nanas, and later on introduced polyester to achieve a more vibrant effect.',
  url: 'https://i.imgur.com/Sd1AgUOm.jpg',
  alt: 'A large mosaic sculpture of a whimsical dancing female figure in a colorful costume emanating joy.'
}, {
  name: 'Ultimate Form',
  artist: 'Barbara Hepworth',
  description: 'This abstract bronze sculpture is a part of The Family of Man series located at Yorkshire Sculpture Park. Hepworth chose not to create literal representations of the world but developed abstract forms inspired by people and landscapes.',
  url: 'https://i.imgur.com/2heNQDcm.jpg',
  alt: 'A tall sculpture made of three elements stacked on each other reminding of a human figure.'
}, {
  name: 'Cavaliere',
  artist: 'Lamidi Olonade Fakeye',
  description: "Descended from four generations of woodcarvers, Fakeye's work blended traditional and contemporary Yoruba themes.",
  url: 'https://i.imgur.com/wIdGuZwm.png',
  alt: 'An intricate wood sculpture of a warrior with a focused face on a horse adorned with patterns.'
}, {
  name: 'Big Bellies',
  artist: 'Alina Szapocznikow',
  description: "Szapocznikow is known for her sculptures of the fragmented body as a metaphor for the fragility and impermanence of youth and beauty. This sculpture depicts two very realistic large bellies stacked on top of each other, each around five feet (1,5m) tall.",
  url: 'https://i.imgur.com/AlHTAdDm.jpg',
  alt: 'The sculpture reminds a cascade of folds, quite different from bellies in classical sculptures.'
}, {
  name: 'Terracotta Army',
  artist: 'Unknown Artist',
  description: 'The Terracotta Army is a collection of terracotta sculptures depicting the armies of Qin Shi Huang, the first Emperor of China. The army consisted of more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.',
  url: 'https://i.imgur.com/HMFmH6m.jpg',
  alt: '12 terracotta sculptures of solemn warriors, each with a unique facial expression and armor.'
}, {
  name: 'Lunar Landscape',
  artist: 'Louise Nevelson',
  description: 'Nevelson was known for scavenging objects from New York City debris, which she would later assemble into monumental constructions. In this one, she used disparate parts like a bedpost, juggling pin, and seat fragment, nailing and gluing them into boxes that reflect the influence of Cubism’s geometric abstraction of space and form.',
  url: 'https://i.imgur.com/rN7hY6om.jpg',
  alt: 'A black matte sculpture where the individual elements are initially indistinguishable.'
}, {
  name: 'Aureole',
  artist: 'Ranjani Shettar',
  description: 'Shettar merges the traditional and the modern, the natural and the industrial. Her art focuses on the relationship between man and nature. Her work was described as compelling both abstractly and figuratively, gravity defying, and a "fine synthesis of unlikely materials."',
  url: 'https://i.imgur.com/okTpbHhm.jpg',
  alt: 'A pale wire-like sculpture mounted on concrete wall and descending on the floor. It appears light.'
}, {
  name: 'Hippos',
  artist: 'Taipei Zoo',
  description: 'The Taipei Zoo commissioned a Hippo Square featuring submerged hippos at play.',
  url: 'https://i.imgur.com/6o5Vuyu.jpg',
  alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
}];

Đây là một mảng, đặt tên là sculptureList, có 12 phần tử, là 12 objects, và được xuất ra để những components khác có thể sử dụng, sử dụng keyword export

Bên trong mỗi object, có 5 properties, là thông tin mà chúng ta sẽ import vào components
 
Tiếp theo, chúng ta sẽ sử dụng 2 state variables để keep track 2 thông tin, đó là object hiện tại đang show và có hiển thị description hay không. Chúng ta sẽ dùng useState hook

JSX:
import { useState } from 'react';
import { sculptureList } from './data.js';

export default function Gallery() {
  const [index, setIndex] = useState(0);
  const [showMore, setShowMore] = useState(false);
 
Có 3 nút (buttons), khi nhấn vào sẽ kích hoạt (trigger) 3 trình xử lý sự kiện (event handlers) là
  • handlePrevClick
  • handleNextClick
  • handleMoreClick
Hãy xem 3 hàm này làm những gì

JSX:
let hasPrev = index > 0;
  let hasNext = index < sculptureList.length - 1;

  function handlePrevClick() {
    if (hasPrev) {
      setIndex(index - 1);
    }
  }

  function handleNextClick() {
    if (hasNext) {
      setIndex(index + 1);
    }
  }

  function handleMoreClick() {
    setShowMore(!showMore);
  }
 
Chúng ta sử dụng 2 biến để xử lý 2 edge cases, là tại object đầu và object cuối. hasPrev trả về true nếu index từ 1 - 11, trả về false nếu index = 0 (object 1). Ngược lại, hasNext trả về true nếu index từ 0 - 10, trả về false nếu index = 11 (object 12)
  • Chỉ trong trường hợp hasPrev = true, thì handlePrevClick mới thực thi, làm nhiệm vụ là setIndex(index - 1)
  • Chỉ trong trường hợp hasNext = true, thì handleNextClick mới thực thi, làm nhiệm vụ là setIndex(index + 1)
Tiếp theo, initial state của showMore = false, nghĩa là theo mặc định, UI sẽ không show description. Khi người vào click vào button Show More, handleMoreClick triggered, nó sẽ set lại state là showMore = true, kích hoạt việc re-render lại, và do đó hiển thị phần mô tả trong UI.

Chúng ta sẽ dùng biến sculpture để lưu object hiện tại
JSX:
let sculpture = sculptureList[index];

Và dùng conditional render để hiện thị ra, tùy theo điều kiện mà người dùng tương tác
JSX:
{showMore ? 'Hide' : 'Show'} details

{showMore && <p>{sculpture.description}</p>}
 
Làm việc với objects khi sử dụng useState hook

Nhìn chung, React sẽ cập nhật những thay đổi do người dùng tạo ra, sau đó hiển thị kết quả ra màn hình theo ba bước
  • Trigger: các sự kiện kích hoạt
  • Render: kết xuất và gọi components
  • Commit: thực hiện những thay đổi vào DOM
Giữa những lần re-render, các biến cục bộ local variables sẽ bị đặt lại về giá trị ban đầu. Đó là lý do mà chúng ta sử dụng useState hook để ghi lại keep track được những thay đổi, sử dụng chúng cho những lần re-renders tiếp theo
JSX:
import {useState} from 'react';

const [number, setNumber] = useState(0);

Khi gọi useState hook về cơ bản là một function. Lệnh gọi phía trên trả về 2 phần
  • Một biến trạng thái state variable
  • Một hàm đặt lại giá trị của biến trạng thái đó state setter function
State variable này như là một local memory của component đó. Nó sẽ không bị đặt lại về giá trị ban đầu giữa những lần re-renders, mà thay vào đó nó sẽ cập nhật dựa trên hàm setNumber.

Tiếp theo, biến trạng thái state variables number có thể lưu bất kỳ kiểu dữ liệu nào
  • Number
  • String
  • Boolean
  • Array
  • Object
Khi làm việc với 3 kiểu dữ liệu nguyên thủy trên cùng, bạn chỉ có thể thay thế replace từ number này sang number khác, mà không chỉnh sửa nó được. Những primitive types này là read-only.
JSX:
number = 0;
setNumber(1);
//số 0 được thay thế bằng số 1, chứ không phải số 0 bị đột biến thành số 1

Tại sao lại phải nói điều này, vì đối với 2 kiểu dữ liệu advanced hơn là array và object, bạn thực sự có thể biến đổi nó, và điều này gây ra lỗi và những hành vi mà developers không đoán được khi lập trình React
JSX:
person = {
    name: 'Ben',
    age: 38,
    isReady: false,
}
JSX:
person.name = 'Ray';
 
Last edited:
1. Lời nói đầu

Hello World.
Nhận thấy trong box Lập trình có nhiều anh chị mới bắt đầu ở entry level nên tôi muốn đóng góp một ít công sức để viết ra và chia sẻ.
Hôm nay trong loạt series hướng dẫn, tôi sẽ đề cập về những nền tảng React cho người mới bắt đầu React for beginners - Fundamentals.
Hy vọng sẽ giúp ích cho những anh chị mới, tìm kiếm sự thành công với mức lương $ 1.000 đầu tiên của mình. Nếu có ích, hãy like và để lại comment.

2. Tại sao là React?

Với những anh chị mới chưa biết bắt đầu từ đâu hẳn sẽ có câu hỏi này.
Đầu tiên chúng ta sẽ là người tạo ra những trang web và ứng dụng applications.
Ví dụ websites: google.com, zing.vn, youtube.com.
Ví dụ applications: ứng dụng Vietcombank, game Angry Birds, hay ứng dụng sách nói Fonos.

Bên trong những ứng dụng này, chúng ta sẽ quan tâm đến hai phần.
  • Nội dung, giao diện, đường link, hình ảnh, video, icons, etc. Nói chung là những gì show ra trước mặt của chúng ta. Người ta gọi đó là User Interface UI, cũng có thể được gọi là FrontEnd, front nghĩa là phía trước.
  • Có một tảng băng chìm lớn hơn, diễn ra đằng sau khi chúng ta lướt web. Đó có thể là dữ liệu - data chúng ta nhập vào, thông tin đăng nhập mà chúng ta lưu - authentification, phân quyền chúng ta có thể làm gì - authorization. Nói tóm là những gì chạy đằng sau, những gì server làm, còn được gọi là BackEnd.

React giải quyết vấn đề đầu tiên, là User Interface.

Các bạn cũng có thể có câu hỏi, tại sao không dùng Wordpress hoặc những công cụ làm website nhanh chóng, chỉ cần kéo và thả drag-and-drop, tiện lợi, không cần học, đơn giản. Well, React có những thế mạnh như sau:
  • Đầu tiên, hệ thống files theo dạng modulars, có là có thể lắp ghép lại với nhau, người ta gọi là components. Có thể hiểu một component là một chức năng và mình có thể sử dụng lại khi cần thiết, không phải viết lại reusable.
  • Ví dụ: website news.zing.vn có 1.000 bài viết. Nếu sử dụng Wordpress, ta phải code 1.000 files khác nhau và phải code lại từng trang một. Nếu muốn thay đổi, cập nhật, hoặc bảo trì, ta phải làm lần lượt 1.000 files khác nhau. Việc này vô cùng tốn kém thời gian và tiền bạc.
  • Ngược lại, React tạo ra một website tĩnh static website. Các bạn có thể hình dung website là một cái khung frame của một ngôi nhà, có các trụ components là cố định không đổi. Muốn tạo 1.000 bài viết khác nhau, chỉ đơn giản là thay đổi phần dữ liệu data bên trong, còn cái khung thì giữ nguyên. Việc này tiết kiệm rất nhiều công sức khi muốn chỉnh sửa và bảo trì.

Để hiểu rõ hơn sự khác biệt giữa React và những công cụ tools làm website đơn giản, kéo và thả, drag-and-drop, anh chị hãy đọc thêm bài viết sau: Wordpress Vs Reactjs: What Should You Choose? (https://www.mindbowser.com/react-vs-wordpress/)

3. Set up môi trường làm việc (dành cho MacOS)

  • Đầu tiên, anh chị sẽ cần một nơi để viết code gọi là code editor. Người ta đã nghĩ ra nhiều công cụ khác nhau để giúp việc viết code trở nên thoải mái, dễ dàng, và thuận tiện. Một trong số đó là Visual Studio Code được rất nhiều người yêu thích. VS Code là một semi-IDE, Intergrated Development Enviroment, nôm na là một nơi anh chị có thể viết code, chạy thử, chỉnh sữa lỗi fix bugs trên đó. Để tải về và cài đặt, hãy truy cập vào Download Visual Studio Code - Mac, Linux, Windows (https://code.visualstudio.com/download)

  • Tiếp theo, mở Terminal được tích hợp sẵn built-in trong VS Code, sử dụng tổ hợp phím tắt Ctrl+Shift+`. Terminal kiểu gần giống như hệ điều hành MS-Dos ngày xưa anh chị học, là nơi để thực thi một số lệnh, ví dụ như cd change directory để thay đổi vị trí thư mục, ls để liệt kê file, mkdir make directory để tạo thư mục.

  • Tại Terminal, chúng ta sẽ sử dụng npm node package manager để bắt đầu dự án: npx create-react-app {tên ứng dụng} sau đó hit enter. React sẽ tự động tải về và cài đặt một số thư mục để giúp các anh chị code, có thể kể đến là node_modules, public, src, .gitignore, package-lock.json, package.json.

  • Sẽ có một số thư mục và files quan trọng, anh chị cần nhớ khi làm việc. Đó là ./public/index.html, ./src/App.js, ./src/App.css, và ./package.json. App.js là root component, là ông tổ của mọi components. Anh chị có thể hình dung đơn giản nó là gốc cây, là nơi khởi thủy của mọi chức năng khác, từ nội dung website, comment, like & upvote cho đến thanh navigation bar. Còn file App.css sẽ đảm nhận vai trò làm đẹp, để trang trí cho page, căn lề chỉnh dòng, font & size và nhiều thứ khác. Nói chung, làm đẹp thì vào App.css, làm chức năng thì vào App.js.

Ok, bây giờ chúng ta bắt tay vào xây dựng website từ những viên gạch đầu tiên nào.

4. Xây dựng tính năng

Mục tiêu của chúng ta là xây dựng một trang web. Một website thông thường sẽ có trang chủ Home Page, thông tin về chủ website và dịch vụ họ cung cấp About Us, và danh sách những bài viết Articles List. Ok here we go.

  • Tạo Home Page và About Us
kiến thức - React cho người mới bắt đầu: Cách tạo một ứng dụng từ a-z (https://voz.vn/t/react-cho-nguoi-moi-bat-dau-cach-tao-mot-ung-dung-tu-a-z.627852/post-20361582)
  • Tạo Navigation Bar và cập nhật vào root component App.js
kiến thức - React cho người mới bắt đầu: Cách tạo một ứng dụng từ a-z (https://voz.vn/t/react-cho-nguoi-moi-bat-dau-cach-tao-mot-ung-dung-tu-a-z.627852/post-20361724)
  • Tạo Article Page để hiển thị thông tin website và Not Found Page khi URLs are invalid
kiến thức - React cho người mới bắt đầu: Cách tạo một ứng dụng từ a-z (https://voz.vn/t/react-cho-nguoi-moi-bat-dau-cach-tao-mot-ung-dung-tu-a-z.627852/post-20361748)
  • Tạo article-content để lưu thông tin tất cả bài viết của anh chị
kiến thức - React cho người mới bắt đầu: Cách tạo một ứng dụng từ a-z (https://voz.vn/t/react-cho-nguoi-moi-bat-dau-cach-tao-mot-ung-dung-tu-a-z.627852/post-20399068)
  • Tạo Articles List Page để hiển thị danh sách tất cả những bài viết của website
kiến thức - React cho người mới bắt đầu: Cách tạo một ứng dụng từ a-z (https://voz.vn/t/react-cho-nguoi-moi-bat-dau-cach-tao-mot-ung-dung-tu-a-z.627852/post-20465761)
  • Giới thiệu React Hooks
kiến thức - React cho người mới bắt đầu: Cách tạo một ứng dụng từ a-z (https://voz.vn/t/react-cho-nguoi-moi-bat-dau-cach-tao-mot-ung-dung-tu-a-z.627852/post-20629303)
Đặt gạch
 
Back
Top