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 :) }
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!
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With