Stop Struggling With React.js


Tuan Duc Tran

React.js là một trong những thư viện front-end phổ biến nhất hiện nay. Nhưng đối với nhiều lập trình viên, đặc biệt là người mới bắt đầu, việc học và làm chủ React không hề dễ dàng. Tin vui là bạn có thể rút ngắn thời gian, giảm bớt khó khăn và nắm vững React nhanh hơn nhờ một số nguyên tắc và “cheat sheet” hữu ích dưới đây.

Import Statements

Để sử dụng React, hooks và các component, bạn cần import chúng vào trong dự án:

MyComponent.jsx
import React from 'react';
import { useState, useEffect } from 'react';
import ComponentName from '/ComponentName';

Mẹo nhỏ: Luôn import những gì bạn cần để giữ code gọn gàng và rõ ràng.

Functional Component

Functional component giúp code sạch và tái sử dụng dễ dàng:

ComponentName.jsx
function ComponentName(props) {
  return (
    <div>
      {/* JSX Code */}
    </div>
  );
}
export default ComponentName;

Class Component

Class component ít phổ biến hơn nhưng vẫn hỗ trợ lifecycle methods:

ComponentName.jsx
import React, { Component } from 'react';
class ComponentName extends Component {
  render() {
    return <div>{/* JSX Code */}</div>;
  }
}
export default ComponentName;

JSX Syntax

JSX cho phép nhúng giá trị động trong dấu {}:

ComponentName.jsx
return (
  <div>
    <h1>{title}</h1>
    <p>{description}</p>
  </div>
);

Props

Props giúp truyền dữ liệu từ component cha sang component con:

ChildComponent.jsx
function ChildComponent(props) {
  return <div>{props.value}</div>;
}

Sử dụng trong cha:

ParentComponent.jsx
<ChildComponent value="Some Value" />

Event Handling

Thêm event handler để xử lý tương tác người dùng:

ComponentName.jsx
function ComponentName() {
  const handleClick = () => {
    // Handle click event
  };
  return <button onClick={handleClick}>Click Me</button>;
}

Conditional Rendering

Sử dụng toán tử ? : hoặc && để hiển thị nội dung có điều kiện:

ComponentName.jsx
function ComponentName({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome Back!</p> : <p>Please Log In</p>}
    </div>
  );
}

Lists and Keys

Dùng map() và key duy nhất để render danh sách:

ComponentName.jsx
function ComponentName({ items }) {
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  );
}

Context API

Tránh “prop drilling” bằng Context API:

ContextName.jsx
import { createContext, useContext } from 'react';
 
const ContextName = createContext();
 
function App() {
  return (
    <ContextName.Provider value={value}>
      {/* Children */}
    </ContextName.Provider>
  );
}
 
const value = useContext(ContextName);

Fragments

Nhóm nhiều phần tử mà không tạo thêm node thừa:

ComponentName.jsx
import { Fragment } from 'react';
 
function ComponentName() {
  return (
    <Fragment>
      <h1>Title</h1>
      <p>Description</p>
    </Fragment>
  );
}

Higher-Order Components (HOC)

HOC bao bọc component để thêm tính năng mới:

withExtraProps.jsx
function withExtraProps(WrappedComponent) {
  return function EnhancedComponent(props) {
    return <WrappedComponent {...props} extraProp="value" />;
  };
}

React Router

Dùng React Router để điều hướng giữa các trang:

App.jsx
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
 
function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

Styling Components

Có thể sử dụng inline styling hoặc CSS Modules:

Inline Styling:

StyledComponent.jsx
const style = { color: 'blue', fontSize: '20px' };
return <div style={style}>Styled Component</div>;

CSS Modules:

StyledComponent.jsx
import styles from '/Component.module.css';
return <div className={styles.className}>Styled with CSS Module</div>;

Cách Học React Nhanh Nhất

  1. Xây dựng dự án: Học đi đôi với hành bằng cách tạo project thực tế.
  2. Hiểu rõ nền tảng: Nắm vững component, state và props trước tiên.
  3. Luyện tập thường xuyên: Viết code hằng ngày để cải thiện kỹ năng.
  4. Đọc tài liệu chính thức: Documentation của React là nguồn đáng tin cậy nhất.
  5. Học qua debugging: Đừng sợ lỗi, vì sửa lỗi chính là học.
  6. Tham gia cộng đồng: Giao lưu, chia sẻ với các dev React khác để học hỏi.
  7. Kiên trì: Học React là một hành trình, đi từng bước một.

Tip cuối cùng: Cách học tốt nhất là tạo ra sản phẩm. Bắt đầu nhỏ, sau đó dần dần chinh phục những dự án lớn hơn.

Với những bước trên, bạn sẽ không còn cảm thấy “vật lộn” với React.js nữa, mà thay vào đó là nắm bắt được sức mạnh thực sự của thư viện này.