hocvietcode.com
  • Trang chủ
  • Học lập trình
    • Lập trình C/C++
    • Lập trình HTML
    • Lập trình Javascript
      • Javascript cơ bản
      • ReactJS framework
      • AngularJS framework
      • Typescript cơ bản
      • Angular
    • Lập trình Mobile
      • Lập Trình Dart Cơ Bản
        • Dart Flutter Framework
    • Cơ sở dữ liệu
      • MySQL – MariaDB
      • Micrsoft SQL Server
      • Extensible Markup Language (XML)
      • JSON
    • Lập trình PHP
      • Lập trình PHP cơ bản
      • Laravel Framework
    • Lập trình Java
      • Java Cơ bản
    • Cấu trúc dữ liệu và giải thuật
    • Lập Trình C# Cơ Bản
    • Machine Learning
  • WORDPRESS
    • WordPress cơ bản
    • WordPress nâng cao
    • Chia sẻ WordPress
  • Kiến thức hệ thống
    • Microsoft Azure
    • Docker
    • Linux
  • Chia sẻ IT
    • Tin học văn phòng
      • Microsoft Word
      • Microsoft Excel
    • Marketing
      • Google Adwords
      • Facebook Ads
      • Kiến thức khác
    • Chia sẻ phần mềm
    • Review công nghệ
    • Công cụ – tiện ích
      • Kiểm tra bàn phím online
      • Kiểm tra webcam online
Đăng nhập
  • Đăng nhập / Đăng ký

Please enter key search to display results.

Home
  • ReactJS
Định tuyến trong ứng dụng React với React Router

Định tuyến trong ứng dụng React với React Router

  • 05-08-2023
  • Toanngo92
  • 0 Comments

Trong React, bộ định tuyến (Routers) giúp tạo và điều hướng giữa các URL khác nhau để xử lý logic khi người dùng muốn truy cập các module khác nhau trên ứng dụng web của bạn. Chúng cho phép người dùng di chuyển giữa các thành phần của ứng dụng trong khi vẫn duy trì trạng thái của người dùng và có thể cung cấp các URL duy nhất cho các thành phần này để làm cho chúng dễ chia sẻ hơn. Với bộ định tuyến, chúng ta có thể cải thiện trải nghiệm người dùng của ứng dụng bằng cách đơn giản hóa việc điều hướng trang web.

React Router là một trong những framework định tuyến phổ biến nhất cho React. Thư viện được thiết kế với các thành phần trực quan để cho phép bạn xây dựng hệ thống định tuyến khai báo cho ứng dụng của mình. Điều này có nghĩa là bạn có thể khai báo chính xác thành phần nào của bạn có một lộ trình nhất định. Với việc khai báođịnh tuyến, bạn có thể tạo các đường dẫn mà người dùng có thể đọc được, giúp quản lý kiến trúc ứng dụng của bạn dễ dàng hơn.

Bước 1: Cài đặt react Router:

npm install react-router-dom

Bước 2: Tạo các component cho các trang khác nhau:

Tạo file Main.js

import React, { Component } from 'react';
import axios from 'axios';

class Main extends Component {
    constructor(props) {
        super(props);
        // send request axios sample
        this.state = {
            products: []
        }
    }

    async componentDidMount() {
        try {
          const response = await axios.get('http://localhost:3000/data.json');
          this.setState({ products: response.data });
          console.log(this.state.products);
        } catch (error) {
          console.error('Error fetching data:', error);
          //this.setState({ error: 'An error occurred while fetching data.' });
        }
    }

    render() {

        return (
            <div>
                {
                    this.state.products.map((item, index) => {
                        return (
                            <div key={index}>
                                <div>{item.name}</div>
                                <div>{item.price}</div>
                                <div>{item.description}</div>
                                <div>{item.image}</div>
                            </div>
                        )
                    })
                }
            </div>
        )
    }
}

export default Main

Tạo file Page2.js

import React, { Component } from 'react';

class Page2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: ""
        }
    }

    render() {

        return (
            <div>
                <h1>Page 2</h1>
                Noi dung sdfsdf
            </div>
        )
    }
}

export default Page2

Tạo Header.js

import "./Header.css";
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';

function Header() {
    // dinh nghia bien la thuoc tinh


    const menus = [
        {
            href: "/",
            label_text: "Home"
        },
        {
            href: "/page2",
            label_text: "Page 2"
        }
    ];


    function tudinghia(e, data) {
        console.log(data);
    }

    return (
        <div className="headerWrap">
            <div className="header">
                <div>Logo</div>
                <nav>
                    <ul>
                        {
                            menus.map((item, index) => {
                                return (
                                    <li ><Link to={item.href}>{item.label_text}</Link></li>
                                )
                            })
                        }
                    </ul>
                </nav>
            </div>
        </div>
    )
}

export default Header;

Sửa file Main.js

Lưu ý, ở v6, chúng ta sử dụng <Routes/> và <Route/>, còn ở v5, chúng ta sử dụng thẻ <Switch/> thay thế.

import logo from './logo.svg';
import './App.css';
import Header from './Header/Header';
import Footer from './Footer/Footer';
import Main from './Main/Main';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Page2 from './Page2/Page2';

function App() {
  return (
    <div>
     
      <BrowserRouter>
        <Header />
        <Routes>
          <Route path="/" element={<Main />} />
          <Route path="/page2" element={<Page2 />} />
        </Routes>
      </BrowserRouter>
      <Footer />
    </div>
  );
}

export default App;

Bài tập

Question 1: 
Create a functional component called Counter with two buttons and a counter
value displayed on the screen.
Use the useState hook to manage the counter state.
When the <Increment> button is clicked, increment the counter by 1.
When the <Decrease&quot> button is clicked, decrease the counter by 1.
When the <Reset&quot> button is clicked, counter = 0.
Render the Counter component in the App component.

Question 2: 
Create a functional component called DataFetcher.
Use the useEffect hook to fetch data from the data.json(or data.js) file located
in the public folder.
Store the fetched data in the component's state.
Render the fetched data on the screen.
Render the DataFetcher component in the App component.

Question 3:
Implement routing in your application using the react-router-dom library.
Create two routes: / and /about.

Create a component called Home to be rendered when the / route is active.
Create a component called About to be rendered when the /about route is
active.
Add navigation links in the Header component to navigate between the routes.

Question 4:
Create a functional component called List that receives an array of items as a
prop. Map over the array and render each item as a list item (<li>).
Render the List component in the App component, passing the data array
from the DataFetcher component as a prop.

Question 5:
Create static components for the Header, Navigation, and Footer.
The Header component should display a title for the application.
The Navigation component should display navigation links.
The Footer component should display copyright information.
Render these components in the App component.

Bài viết liên quan:

useMemo trong ReactJS
Giới thiệu Redux và quản lý state với Redux trong React
Gọi API trong React với useEffect Hook
Xử lý tải dữ liệu bất đồng bộ (Async Data Loading), lazyload trong React
Xử lý Form (biểu mẫu) trong React
Xử lý các sự kiện trong DOM và Window bằng React
Debug (gỡ lỗi) React component thông qua React Developer Tools
khái niệm React Context và chia sẻ state qua các component với React Context
Cách quản lý state(trạng thái) bằng Hooks trên React Component
React strict mode (chế độ phát triển) trong React
Quản lý state (trạng thái) trong React Class Component
Hướng dẫn định kiểu (style) cho React Component

THÊM BÌNH LUẬN Cancel reply

Dịch vụ thiết kế Wesbite

NỘI DUNG MỚI CẬP NHẬT

2. PHÂN TÍCH VÀ ĐẶC TẢ HỆ THỐNG

1. TỔNG QUAN KIẾN THỨC THỰC HÀNH TRIỂN KHAI DỰ ÁN CÔNG NGHỆ THÔNG TIN

Hướng dẫn tự cài đặt n8n comunity trên CyberPanel, trỏ tên miền

Mẫu prompt tạo mô tả chi tiết bối cảnh

Một số cải tiến trong ASP.NET Core, Razor Page, Model Binding, Gabbage collection

Giới thiệu

hocvietcode.com là website chia sẻ và cập nhật tin tức công nghệ, chia sẻ kiến thức, kỹ năng. Chúng tôi rất cảm ơn và mong muốn nhận được nhiều phản hồi để có thể phục vụ quý bạn đọc tốt hơn !

Liên hệ quảng cáo: [email protected]

Kết nối với HỌC VIẾT CODE

© hocvietcode.com - Tech888 Co .Ltd since 2019

Đăng nhập

Trở thành một phần của cộng đồng của chúng tôi!
Registration complete. Please check your email.
Đăng nhập bằng google
Đăng kýBạn quên mật khẩu?

Create an account

Welcome! Register for an account
The user name or email address is not correct.
Registration confirmation will be emailed to you.
Log in Lost your password?

Reset password

Recover your password
Password reset email has been sent.
The email could not be sent. Possible reason: your host may have disabled the mail function.
A password will be e-mailed to you.
Log in Register
×