xxxxxxxxxx
// Get query parameters in form of object in react
// it automatically detects the url, however one can also provide it
const queryParams = (url = null) => {
const paramsObj = new URLSearchParams(url ? url : window.location.search);
let newObj = {};
for (const [key, value] of paramsObj) {
newObj[key] = value;
}
return newObj;
};
export default queryParams;
// Usage in a component
// Url: http://localhost:3000/properties?query=false&search=true
const params = queryParams()
console.log(params) // Object { query: "false", search: "true" }
xxxxxxxxxx
import { useSearchParams } from "react-router-dom";
const [searchParams] = useSearchParams();
console.log(searchParams.get("type"));
xxxxxxxxxx
const params = new URLSearchParams();
params.append('customerId', `${customerId}`);
return await fetchCustomers(`customers/${params}`)
xxxxxxxxxx
new URLSearchParams(this.props.location.search).get("your_query_param_key")
xxxxxxxxxx
localhost:8080/users?name=shana
// In this url key is name and value is shana
// We can pass query params to the Link component like this.
<Link to={{pathname:"/users",search: "?name=shana"}}>Shana</Link>
//or
<Link to="/users/?name=shana">Shana</Link>
//To access the query params from a url, we need to use the react router useLocation hook.
//Users.js
import React from 'react';
import {useLocation} from "react-router-dom";
function Users() {
const location = useLocation();
console.log(location);
return (
<div>
<h1>Users page</h1>
<p>{new URLSearchParams(location.search).get('name')}</p>
</div>
);
}
//In class-based components, we can access the query params using this.props.location object.
import React from 'react';
class Users extends React.Component{
render(){
const search = this.props.location.search;
return <p>{new URLSearchParams(location.search).get('name')}</p>
}
}