URL Router in React

Nay mình chia sẻ cách sử dụng Router trong React. Router là một phần rất quan trọng trong React, nó giúp ta cấu hình các định tuyến đường dẫn URL của các Component. Để sử dụng được ta cần phải thông qua thư viện mà React đã hổ trợ ta, đó là thư viện "react-router-dom"
Ok, Cài đặt project name "url-router-react"

npx create-react-app url-router-react
cd url-router-react
npm install react-router-dom

Trong Demo project này, ta sẽ tạo một chức năng xem thông tin của Product, bao gồm có các Component như sau:
+ src/components/Home.js : Hiển thị thông tin Product
+ src/components/Detail.js : Thông tin về Product được chọn 

Mình sẽ lấy danh sách Products từ API:https://5adc8779b80f490014fb883a.mockapi.io/products . Vì thế ta cần install axios để sử dụng Restful API
npm install axios
+ Tạo file theo đường dẫn str/components/api/index.js 

import axios from 'axios';
let API_URL = 'https://5adc8779b80f490014fb883a.mockapi.io';
   export default function callApi(endpoint, method = 'GET', body) {
       return axios({
           method,
           url: `${API_URL}/${endpoint}`,
           data: body
       }).catch(err => {
           console.log(err);
       });
   }

+ Tạo Home.js trong src/components , gọi api để trả về data,hiển thị Products ra cho người dùng! Bạn có thể xem lại Render Data in React 

import React, { Component } from 'react'
import {Link} from 'react-router-dom'
import callApi from './api'
class Home extends Component {
    constructor(props){
        super(props)
        this.state = {
            loading:false,
            _products:[]
        }
    }
    componentDidMount(){
        //CALL API https://5adc8779b80f490014fb883a.mockapi.io/products 
        callApi("/products",'GET',null).then(res => {
            this.setState({
                loading:true,
                _products:res.data
            })
        });
    }
    render() {
        const {loading,_products} = this.state;
        if(!loading){
            return (
                <div>
                    <h4>Loading...</h4>
                </div>
            )
        }
        return (
            <div>
                <h1>List Product</h1>
                <ul style={{display:'flex',flexWrap:'wrap'}}>
                    {
                        _products.map((item,index)=>(
                            <li key={index} style={{
                                width:'calc(100% / 4 - 20px)',
                                heigth:'80px',
                                listStyle:'none',
                                paddingRight:'20px',
                                boxSizing:'border-box',
                                margin:'10px',
                                border:'1px solid #ccc'
                            }}>
                                <h5>{item.name}</h5>
                                <strong>price : {item.price}</strong>
                                <br/>
                                <Link to= {`/detail/${item.id}`}>Xem</Link>
                            </li>
                        ))
                    }
                </ul>
            </div>
        )
    }
}

export default Home

+ Tạo file Detail.js trong src/components, dùng hiển thị product mà người dùng bấm xem

import React, { Component } from 'react'
import callApi from './api'
class Detail extends Component {
   constructor(props){
       super(props)
       this.state = {
           check:false,
           _product:{}
       }
   }
   componentDidMount(){
       let id = this.props.match.params.id; 
       callApi(`/products/${id}`,'GET',null).then(res=>{
            this.setState({
                check:true,
                _product:res.data
            })
       })
   }
   render(){
       const {check,_product} = this.state;
       if(!check){
           return(
               <div>loading...</div>
           )
       }
       return(
           <div>
               <h2>{_product.name}</h2>
               <strong>{_product.price} $</strong>
           </div>
       )
   }
}

export default Detail

Đoạn code trên ta cần tạo _product & check trong State, giúp xác định trạng thái của ứng dụng

this.state = {
           check:false,
           _product:{}
       }

Để nhận được tham số trên URL Router:  /detail/:id  ta dùng đoạn code sau:

let id = this.props.match.params.id; 

Sử dụng hàm callApi để restful từ đường dẫn /products/:id , trả về data, sau đó ta dùng setState cập nhật lại dữ liệu trạng thái ban đầu

callApi(`/products/${id}`,'GET',null).then(res=>{
            this.setState({
                check:true,
                _product:res.data
            })
       })

+ Mở file App.js trong src, cấu hình Router cho Component

import React from 'react';
import './App.css';
import { BrowserRouter as Router,Switch,Route,Link} from 'react-router-dom'
import Home from './components/Home'
import Detail from './components/Detail'
function App() {
  return (
    <div className="App">
       
       <Router>
           <div>
              <ul className="menu">
                  <li><Link to="/">Home</Link></li>
                  <li><Link to="/products">Products</Link></li>
              </ul>
           </div>
           <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/products" component={Home} />
              <Route path="/detail/:id?" component={Detail} /> 
           </Switch>
       </Router>
    </div>
  );
}

export default App;

Chúng ta cần import thư viện cấu hình Router

import { BrowserRouter as Router,Switch,Route,Link} from 'react-router-dom'

Để trỏ tới Component, ta cần cấu hình các path cho Component

<Switch>
              <Route path="/" exact component={Home} />
              <Route path="/products" component={Home} />
              <Route path="/detail/:id?" component={Detail} /> 
           </Switch>

Ok, vậy là xong, giờ ta thử : npm start xem hoạt động của nó 

URL Router in React

URL Router in React

Nếu bạn muốn dùng Query Parameters trên URL cũng được , VD: http://localhost:3000/detail?name=iphone&id=123

Để lấy tất cả tham số trên đường dẫn URL trên bạn dùng đoạn code sau:

this.props.location.search

Bạn console nó ra sẽ thế này ?name=iphone&id=123, để cho thuận tiện sử dụng bạn cài cho mình thư viện sau đây, để chuyển đổi cái chuổi trả về thành một đối tượng (Object), sao đó ta chỉ việc trỏ tới từng phần tử để lấy giá trị ra thôi

npm install query-string

Sau khi cài xong, bạn cần khai báo thư viện trong file Component mà bạn muốn dùng: import queryString from 'query-string'

//URL : http://localhost:3000/detail?name=iphone&id=123
let params = queryString.parse(this.props.location.search)
console.log(params)
//Object { id: "123", name: "iphone" }

Vậy ta dễ dàng xử lý hơn!

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)