Home > OS >  How to read the ref code from URL in react js
How to read the ref code from URL in react js

Time:05-19

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.

CodePudding user response:

You also get value of ref from this way :

const queryString = window.location.search;
const parameters = new URLSearchParams(queryString);
const value = parameters.get('ref');

CodePudding user response:

You may try this:

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

CodePudding user response:

You can use browser native api

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

CodePudding user response:

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);
  return <span>{searchParams.get(name)}</span>;
};

To use:

<UrlSearchParamValue name='ref' />;
  • Related