Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get query string using React?

Tags:

reactjs

I'm trying to get "query=123" from the url http://localhost:3000/?query=123. Tried

//App.js const search = this.props.location.search; const params = new URLSearchParams(search); const foo = params.get('foo');  console.log(this.props); 

and my console shows this https://d.pr/i/w5tAYF which doesn't show location.search anywhere... any idea how I would get the query string?

like image 986
Tina Avatar asked Oct 04 '18 17:10

Tina


People also ask

How do I get query string in React?

Get a single Query String value location.search object: import React from 'react'; import { useSearchParams } from 'react-router-dom'; const Users = () => { const [searchParams] = useSearchParams(); console. log(searchParams); // ▶ URLSearchParams {} return <div>Users</div>; };

How do you get the parameter value from React?

Getting search parameters using windowconst App = () => { const params = new URLSearchParams(window. location. pathname); return <p>{params.

How do I get query parameters in React router v5?

Again, in order to get access to the URL Parameter with React Router v5, you use the useParams Hook. Now that we have our links and the component to render, let's create our Route with a URL Parameter. Like we saw earlier with Twitter, the pattern we want to use is /:account . And that's it.


2 Answers

React doesn't handle URL search parameters. You need to look in the window object for them instead. Here's how you would get the value of query:

let search = window.location.search; let params = new URLSearchParams(search); let foo = params.get('query'); 
like image 83
Adam Avatar answered Oct 01 '22 04:10

Adam


I created a separate function for the query string.

function useQuery() {   return new URLSearchParams(window.location.search); } 

Then I can provide the query string I want to get. In your case its query

  let query = useQuery().get('query'); 
like image 40
Khondoker Zahidul Hossain Avatar answered Oct 01 '22 03:10

Khondoker Zahidul Hossain