Taylor swift
Taylor swift

Reputation: 23

Get url parameter from react-router and use in Component

I want to get id parameter from the URL of this react-router (App.js):

import React from "react";
import ReactDOM from "react-dom";
import Main from "./ui.js";
import Master from "./master.js";
import FireCess from "./FireCess";
import { Component } from "react";
import { BrowserRouter, Route,Link, Switch } from "react-router-dom";

class App extends Component{
    render(){
        return(
        <div className="root">
        <BrowserRouter>
          <Switch>
          <Route exact path="/masters/:id/PropertyTax/FireCess" component={FireCess}/>
          <Route exact path="/masters/pb/tenant/tenants" component={Master} />
          <Route exact path='/' component={Main} />
           
          </Switch>
        </BrowserRouter>
      </div>
        );
    }
}

export default App

I want to use that id parameter in the other URL inside the FireCess component (FireCess.js):

import React from "react";
import Admin from "react-crud-admin";
import Form from "react-jsonschema-form";
import axios from "axios";
import Select from 'react-select';
import Master from "./master.js";

import { BrowserRouter, Route,Link, Switch, useParams } from "react-router-dom";

import "react-crud-admin/css"; //optional css import


export default class FireCess extends Admin {
  constructor(props) {
    super();
   
    
    this.name = "Tenant";
    this.name_plural = "Tenants";
    this.list_display_links = ["rate"];
    this.list_display = ["rate","fromFY"];
   
    this.list_per_page = 10;
  

  
  }
  

  get_queryset(page_number, list_per_page, queryset) {

    axios.get("/masters/:id/PropertyTax/FireCess",{
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
    
    }).then(response => {

   
      this.set_queryset(response.data);

    });

    return queryset;


  }
  }

How do I get id parameter inside the component?

I have tried using this.props.match.params.id but got an error saying:

TypeError: Cannot read property 'match' of undefined.(react-router version is ^5.2.0)

Upvotes: 1

Views: 209

Answers (1)

Alex Yepes
Alex Yepes

Reputation: 1195

You haven't defined :id in your url, that is why it's undefined in your error, so instead of this

axios.get("/masters/:id/PropertyTax/FireCess",{
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }

declare a varible that represents the id; something like:

const id = yourId;

axios.get(`/masters/${id}/PropertyTax/FireCess`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }

Upvotes: 2

Related Questions