Lucky
Lucky

Reputation: 217

How to read the ref code from URL in react js

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

Answers (4)

Yosvel Quintero
Yosvel Quintero

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

hamid mehmood
hamid mehmood

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

BIPUL MANDOL
BIPUL MANDOL

Reputation: 289

You can use browser native api

const query = new URLSearchParams(window.location.search);
console.log(query.get(ref))

Upvotes: 0

Ashish
Ashish

Reputation: 182

You may try this:

${window.location.search.split('=')[1]}

Upvotes: 1

Related Questions