Reputation: 217
I want to get the ref code from the URL, http://localhost:3000/?ref=2926
I try with const session = ${window.location.href}
; it gets the full current URL and tries to use split() the pathname but it didn't work, how to get only the ref code from the URL.
Upvotes: 1
Views: 712
Reputation: 19080
You can use URL.searchParams
const { searchParams } = new URL(document.location)
Code:
const { searchParams } = new URL('http://localhost:3000/?ref=2926')
console.log(searchParams.get('ref'))
React component:
export const UrlSearchParamValue = ({ name }) => {
const { searchParams } = new URL(document.location)
const value = searchParams.get(name)
return <span>{value}</span>
};
To use:
<UrlSearchParamValue name='ref' />
Upvotes: 0
Reputation: 196
You also get value of ref from this way :
const queryString = window.location.search;
const parameters = new URLSearchParams(queryString);
const value = parameters.get('ref');
Upvotes: 2
Reputation: 289
You can use browser native api
const query = new URLSearchParams(window.location.search);
console.log(query.get(ref))
Upvotes: 0