Virus Corona (Covid-19)

Dapatkan Informasi terbaru

Contoh Cara Get Parameter Kueri di React

If Man 28 Nov 2020 39

Parameter kueri ditunjukkan dengan yang pertama  ? dalam URI. Pada artikel ini, saya akan membagikan cara mendapatkan parameter kueri di React. Mari kita mulai:

React Router v5

Di react-router v5, kita bisa mendapatkan parameter kueri menggunakan useLocationhook. Kita perlu mengimpor BrowserRouter dari paket react-router-dom .

Instal react-router-do m jika tidak diinstal:

npm i react-router-dom

Buka index.js dan impor BrowserRouter .

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

/* import BrowserRouter */
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

Buka App.js dan tempel kode ini:

import React from 'react';
import { useLocation } from 'react-router-dom';

function App() {
  const search = useLocation().search;
  const product_id = new URLSearchParams(search).get('product_id');
  const category_id = new URLSearchParams(search).get('category_id');
  
  return (
    <div>
      <p>Product ID: {product_id}</p>
      <p>Category ID: {category_id}</p>
    </div>
  );
}

export default App;

Sekarang kunjungi route ini dan lihat hasilnya:

http://localhost:3000?product_id=102&category_id=10

React Router v4

Menggunakan props.location.search properti, kita bisa mendapatkan parameter di react router 4. Mari kita lihat contoh:

import React from 'react';

export default function Product(props) {

  const search = props.location.search;
  const product_id = new URLSearchParams(search).get('product_id');

  return (
    <div>
      <p>Product ID: {name}</p>
    </div>
  );
}

Class-based Component

Dalam  class-based components, Anda bisa mendapatkan params seperti ini:

import React, { Component } from "react";

class Product extends Component {

  render() {
    const search = this.props.location.search;
    const product_id = new URLSearchParams(search).get("product_id");

    return (
      <div>
      <p>Product ID: {product_id}</p>
      </div>
    );
  }
}

export default Product;

Itu dia. Terima kasih sudah membaca.🙂

Tags

get params in react example react router

Related Stories


Latest Stories


SEARCH

If Man
2 Followers
I'm an AI student who attempts to find simple explanations for questions and share them with others

TOP ARTICLE

Cara Membuat Composer PHP Package
Adul Azis 26 Jun 2022

OTHER POST