Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs get URL pathname id

I want to get id from URL to load data from API, using React JS

let url = 'http://localhost:3000/View/22'; //window.location.href originally instead of this
let object = new URL(url);
let path = object.pathname
console.log(path) 
//

console.log(path.split('/').pop())

I can get this id by split() but it's seems dirty, right? Is there a clean way or native way to get this? Also I am wondering, maybe this is not right way to get id and pass it to API , am I right? maybe there will be security issue, if someone enter /View/22/22/33/44/ it get 44 not 22

I am new to React, is there native way or correct way to get page id, and pass it to API?

like image 267
danny cavanagh Avatar asked Apr 18 '26 10:04

danny cavanagh


1 Answers

Use this.props.match.params.id

const id = this.props.match.params.id;
console.log(id)

In router:

<Route exact path='/View/:id' component={View}></Route>
like image 125
Pedram Avatar answered Apr 21 '26 01:04

Pedram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!