danny cavanagh
danny cavanagh

Reputation: 135

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?

Upvotes: 3

Views: 4995

Answers (4)

Pedram
Pedram

Reputation: 16575

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>

Upvotes: 4

gnujoow
gnujoow

Reputation: 374

if you are unsing react-router for your app, you can get your url parameter with useParams() hook.

check following link. https://reacttraining.com/react-router/web/example/url-params

Upvotes: 2

Spacetoaster
Spacetoaster

Reputation: 59

What you probably want to do is use something like react-router, define routes and get the parameters inside a component.

Upvotes: 2

Vincent J. Michuki
Vincent J. Michuki

Reputation: 549

Try this:

 let url = 'http://localhost:3000/View/22';
 var id = url.substring(url.lastIndexOf('/') + 1);

Upvotes: 0

Related Questions