Chuyển đến nội dung chính

React: Complex Component- Day 4

Trong bài viết này, chúng ta sẽ xây dựng giao diện từ project html-javascript-css cho đến project sử dụng react app.

Giao diện trang web

Giao diện bao gồm: HTML5 + Bootstrap 5
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap 5 Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container-fluid p-5 bg-primary text-white text-center">
  <h1>My First Bootstrap Page</h1>
  <p>Resize this responsive page to see the effect!</p> 
</div>
  
<div class="container mt-5">
  <div class="row">
    <div class="col-sm-4">
      <h3>Column 1</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
    <div class="col-sm-4">
      <h3>Column 2</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
    <div class="col-sm-4">
      <h3>Column 3</h3>        
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
      <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
    </div>
  </div>
</div>

</body>
</html>

Tạo ứng dụng React bằng cách tự tạo file HTML, CSS và JavaScript

Quay trở lại Day-1, chúng ta có app ReactJs bằng cách thêm react.js và react-dom.js
<!DOCTYPE html>
<html>

<head>
  <title>Hello React</title>
  <meta charset="utf-8">
</head>

<body>
  <div id="app">
    <!-- my app renders here -->
  </div>
  <script src="react/react.js"></script>
  <script src="react/react-dom.js"></script>
  <script>
    // my app's code
  </script>
</body>

</html>
Sau khi thêm bootstrap và react library
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJs - Hello World</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
      crossorigin="anonymous" />
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-sm">
          <div id="app">      <!-- my app renders here -->
          </div>
        </div>
      </div>
    </div>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN"></script>
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossoriginsrc="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
      <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
      ReactDOM.render(
      <h1 id="my-heading">
        <span>Hello <em>Wonderful</em></span> world!
      </h1>,
      document.getElementById('app')
    );
    </script>
  </body>
</html>
Chúng ta chọn JSX vì JSX giúp code React dễ đọc và hiểu hơn. Bạn có thể nhìn thấy cấu trúc của giao diện người dùng một cách rõ ràng, không bị phân tán bởi các dấu ngoặc hay dấu phẩy.
Một vấn đề phát sinh là trong đoạn HTML, chúng ta có 2 thẻ HTML. Để chứa 2 thẻ HTML, có các cách sau:
  • Sử dụng 1 thẻ HTML bên ngoài (vd như thẻ div), hoặc 1 custom component.
    function MyComponent() {
      return (
        <div>
          <h1>Hello</h1>
          <p>World</p>
        </div>
      );
    }
  • Sử dụng Array
    function MyComponent() {
      return [
        <h1 key="heading">Xin chào</h1>,
        <p key="paragraph">Thế giới</p>
      ];
    }
  • Sử dụng 1 fragment
    function MyComponent() {
      return (
        <React.Fragment>
          <h1>Hello</h1>
          <p>world</p>
        </React.Fragment>
      );
    }
    
    // hoặc
    
    function MyComponent() {
      return (
        <>
          <h1>Hello</h1>
          <p>world</p>
        </>
      );
    }
<div class="container-fluid p-5 bg-primary text-white text-center">
	...
</div>

<div class="container mt-5">
  ...
</div>

Vì vậy chúng ta tách ra làm 3 component, 1 component chứa Header, 1 component chứa Body text, và 1 component chứa Header và Body text

Header
const Header = function () {
  return <div class="container-fluid p-5 bg-primary text-white text-center">
	<h1>My First Bootstrap Page</h1>
	<p>Resize this responsive page to see the effect!</p>
  </div>;
};
Article
const Article = function () {
  return <div class="container mt-5">
	<div class="row">
	  <div class="col-sm-4">
		<h3>Column 1</h3>
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
		<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
	  </div>
	  <div class="col-sm-4">
		<h3>Column 2</h3>
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
		<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
	  </div>
	  <div class="col-sm-4">
		<h3>Column 3</h3>
		<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
		<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
	  </div>
	</div>
  </div>;
};
Post
class Post extends React.Component {
  render() {
	return (
	  <div>
		<Header />
		<Article />
	  </div>
	);
  }
}
Cập nhật lại thẻ div chứa app

<div id="app">

</div>
Cập nhật lại React DOM
ReactDOM.render(
  <Post />,
  document.getElementById('app')
);

Tạo ứng dụng bằng Create React App

Sau khi tạo ứng dụng bằng create-react-app, bạn sẽ có câu trúc folder như sau:
└──📁 node_modules
└──📁 public
└──📁 src
└──App.css
└──App.js
└──index.css
└──index.js
└──logo.svg
└──reportWebVital.js
└──setupTests.js
└──.gitignore
└──package-lock.json
└──package.json
└──README.md
Bạn tạo folder components trong folder src để chứa 3 components: Header, Artitle, và Post
└──📁 node_modules
└──📁 public
└──📁 src
└──📁 components
└──Article.js
└──Header.js
└──Post.js
Thêm bootstrap vào public/index.html
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
Thêm file Header.js vào folder src/components
const Header = function () {
  return <div class="container-fluid p-5 bg-primary text-white text-center">
    <h1>My First Bootstrap Page</h1>
    <p>Resize this responsive page to see the effect!</p>
  </div>;
};

export default Header
Thêm file Article.js vào folder src/components
const Article = () => {
    return (<div class="container mt-5">
      <div class="row">
        <div class="col-sm-4">
          <h3>Column 1</h3>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
          <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
        </div>
        <div class="col-sm-4">
          <h3>Column 2</h3>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
          <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
        </div>
        <div class="col-sm-4">
          <h3>Column 3</h3>
          <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
          <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
        </div>
      </div>
    </div>);
  };

export default Article
Thêm file Post.js
import React, { Component } from 'react';
import Header from './Header';
import Article from './Articles';

class Post extends React.Component {
    render() {
      return (
        <div>
          <Header />
          <Article />
        </div>
      );
    }
  }

export default Post
App.js
import './App.css';
import Post from './components/Post';

function App() {
  return (
    <Post />
  );
}

export default App;

Tạo ứng dụng bằng Vite

Trong phần này, mình sẽ hướng dẫn bạn tạo nhanh ứng dụng React bằng Vite Mở terminal, gõ
yarn create vite
yarn create v1.22.10
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Installed "create-vite@2.9.0" with binaries:
- create-vite
- cva
? Project name: » react-demo-layout
Chọn React
? Select a framework: » - Use arrow-keys. Return to submit.
Vanilla
Vue
> React
Preact
Lit
Svelte
Others
Rồi chọn Javascript
?? Select a variant: » - Use arrow-keys. Return to submit.
> JavaScript
TypeScript
JavaScript + SWC
TypeScript + SWC
Để start project, bạn gõ
cd react-demo-layout
yarn
yarn run dev

Các thao tác thêm các file tương tự như phần trước bạn đã làm, lưu ý là lưu file định dạng jsx nha, vd như: Article.jsx, Header.jsx, Post.jsx 

Remove thêm tất cả css trong file index.css với app.css

Sử dụng typescript (bổ sung 2025)

Trong phần này, mình cũng tạo project bằng Vite, ở bước variant, thay vì chọn Javascript, chúng ta chọn TypeScript. Sau đó chúng ta chỉnh sửa lại header và cho phép pass parameters

npm create vite@latest
Need to install the following packages:
create-vite@6.5.0
Ok to proceed? (y) y


> npx
> create-vite

│
◇  Project name:
│  react-getting-started
│
◇  Select a framework:
│  React
│
◇  Select a variant:
│  TypeScript + SWC
│
◇  Scaffolding project in D:\Practices\ReactJs\react-getting-started...
│
└  Done. Now run:

cd react-getting-started
npm install
npm run dev

Mình sẽ bỏ qua các bước tạo file Header.tsx, Post.tsx vì cách làm tương tự như tạo file Header.js, Post.js

Chỉnh sửa file Header có nội dung như sau:
interface HeaderProps {
    title: string;
    subTitle: string;
}

const Header = ({title, subTitle}: HeaderProps) => {
  return <div className="container-fluid p-5 bg-primary text-white text-center">
	<h1>{title}</h1>
    <p>{subTitle}</p>
	<p>Resize this responsive page to see the effect!</p>
  </div>;
}

export default Header;
Cập nhật lại Post.tsx
import Article from "../Article/Article";
import Header from "../Header/Header";

const Post = () => {
    const header = {
        title: "Samsung Galaxy S25",
        subTitle: "The latest flagship smartphone from Samsung"
    }
    return (
        <>
        <div>
            <Header {...header} />
            <Article />
        </div>
        </>
    );

}

export default Post;
Bạn có thể gọi Header và pass parameters theo cách đơn giản hơn:
<Header title="Post Page" subTitle="This is a sample blog post" />
title và subTitle là thuộc tính (props) truyền từ component Post sang Header.

Nếu bạn định nghĩa header trong Post.tsx, bạn có thể truyền toàn bộ object header vào component Header bằng cách sử dụng toán tử spread (...)

<Header {...header} />
...header sẽ "trải" object ra như sau:
<Header title="Samsung Galaxy S25" subTitle="The latest flagship smartphone from Samsung" />
Tóm lại
Cách viết Kết quả trong React
<Header title="..." subTitle="..." /> props = {'{ title, subTitle }'}
<Header {...header} /> props = {'{ ...header }'} ⇒ {'{ title, subTitle }'}

Tham khảo

Nhận xét

Bài đăng phổ biến từ blog này

[ASP.NET MVC] Authentication và Authorize

Một trong những vấn đề bảo mật cơ bản nhất là đảm bảo những người dùng hợp lệ truy cập vào hệ thống. ASP.NET đưa ra 2 khái niệm: Authentication và Authorize Authentication xác nhận bạn là ai. Ví dụ: Bạn có thể đăng nhập vào hệ thống bằng username và password hoặc bằng ssh. Authorization xác nhận những gì bạn có thể làm. Ví dụ: Bạn được phép truy cập vào website, đăng thông tin lên diễn đàn nhưng bạn không được phép truy cập vào trang mod và admin.

ASP.NET MVC: Cơ bản về Validation

Validation (chứng thực) là một tính năng quan trọng trong ASP.NET MVC và được phát triển trong một thời gian dài. Validation vắng mặt trong phiên bản đầu tiên của asp.net mvc và thật khó để tích hợp 1 framework validation của một bên thứ 3 vì không có khả năng mở rộng. ASP.NET MVC2 đã hỗ trợ framework validation do Microsoft phát triển, tên là Data Annotations. Và trong phiên bản 3, framework validation đã hỗ trợ tốt hơn việc xác thực phía máy khách, và đây là một xu hướng của việc phát triển ứng dụng web ngày nay.

Tổng hợp một số kiến thức lập trình về Amibroker

Giới thiệu về Amibroker Amibroker theo developer Tomasz Janeczko được xây dựng dựa trên ngôn ngữ C. Vì vậy bộ code Amibroker Formula Language sử dụng có syntax khá tương đồng với C, ví dụ như câu lệnh #include để import hay cách gói các object, hàm trong các block {} và kết thúc câu lệnh bằng dấu “;”. AFL trong Amibroker là ngôn ngữ xử lý mảng (an array processing language). Nó hoạt động dựa trên các mảng (các dòng/vector) số liệu, khá giống với cách hoạt động của spreadsheet trên excel.