Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get id from url in react.js

i just want to make Ajax request to fetch data from API in REACT.JS, but every API need (id), i want to get that id from URL in browser, how can i do that? this is my code:

componentDidMount(){
fetch("http://localhost:8000/personal/1")
.then(res => res.json())
.then(json => {
    this.setState({
        isLoaded: true,
        information: json,
    })
})

i make the API by Laravel, and every thing work good with this code above, but as i said, i want to get the id from url in browser not just write it as now, thank you :) }

like image 285
Osama Mohammed Avatar asked Aug 10 '19 17:08

Osama Mohammed


People also ask

How do I get the URL ID in react JS?

Use the useParams() hook to get the ID from a URL in React, e.g. const params = useParams() . The useParams hook returns an object of key-value pairs of the dynamic params from the current URL that were matched by the Route path. Copied!

How do I fetch ID in react?

To get the id of the element on click in React: Set the onClick prop on the element to a function. Access the id of the element on the currentTarget property of the event . For example, event.currentTarget.id returns the element's id .

How do I find the URL ID in react hooks?

In React Hooks, You should use useParams() . ex – This is your url – http://localhost:8000/personal/1 . now, if you do console. log(id) , it will give you the exact id of the url.

Can we give ID in react?

Let's start with id attribute in React JS and here we have used id attribute to access one of the elements in a React Component. In this IdComponent component, we are performing the following operations: When a user focuses on a text field, it will change the border-color to blue and backgroun-color to light black.


2 Answers

In React Hooks, You should use useParams(). ex - This is your url - http://localhost:8000/personal/1.

So in this case, use const { id } = useParams()

now, if you do console.log(id), it will give you the exact id of the url. In this case, it will give you 1.

useParams() extracts the id from the url and lets us use it.

like image 136
Abnish Avatar answered Oct 23 '22 02:10

Abnish


Approach #1

You can make use of the history prop from react-router-dom, here is a link that explains how to do so in detail,

https://tylermcginnis.com/react-router-programmatically-navigate/

Approach #2

If you want to make it super simple, then how about making use of the window.location object?

Suppose you are on a page with the url http://localhost:8000/personal/1

window.location.href would give http://localhost:8000/personal/1

window.location.pathname would give /personal/1

Once you have the pathname or href you can use your regular string functions like split(...) and get the ID.

like image 8
Ramaraja Ramanujan Avatar answered Oct 23 '22 02:10

Ramaraja Ramanujan