score:158
note: copy / pasted from comment. be sure to like the original post!
writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. i use this command to lookup the query params in my components:
this.props.location.query
it creates a hash of all available query params in the url.
update:
for react-router v4, see this answer. basically, use this.props.location.search
to get the query string and parse with the query-string
package or urlsearchparams:
const params = new urlsearchparams(paramsstring);
const tags = params.get('tags');
score:0
you may get the following error while creating an optimized production build when using query-string module.
failed to minify the code from this file: ./node_modules/query-string/index.js:8
to overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.
import querysearch from "stringquery";
var query = querysearch(this.props.location.search);
score:3
simple js solution:
querystringparse = function(string) {
let parsed = {}
if(string != '') {
string = string.substring(string.indexof('?')+1)
let p1 = string.split('&')
p1.map(function(value) {
let params = value.split('=')
parsed[params[0]] = params[1]
});
}
return parsed
}
and you can call it from anywhere using:
var params = this.querystringparse(this.props.location.search);
hope this helps.
score:4
after reading the other answers (first by @duncan-finney and then by @marrs) i set out to find the change log that explains the idiomatic react-router 2.x way of solving this. the documentation on using location (which you need for queries) in components is actually contradicted by the actual code. so if you follow their advice, you get big angry warnings like this:
warning: [react-router] `context.location` is deprecated, please use a route component's `props.location` instead.
it turns out that you cannot have a context property called location that uses the location type. but you can use a context property called loc that uses the location type. so the solution is a small modification on their source as follows:
const routecomponent = react.createclass({
childcontexttypes: {
loc: proptypes.location
},
getchildcontext() {
return { location: this.props.location }
}
});
const childcomponent = react.createclass({
contexttypes: {
loc: proptypes.location
},
render() {
console.log(this.context.loc);
return(<div>this.context.loc.query</div>);
}
});
you could also pass down only the parts of the location object you want in your children get the same benefit. it didn't change the warning to change to the object type. hope that helps.
score:10
with stringquery package:
import qs from "stringquery";
const obj = qs("?status=approved&page=1limit=20");
// > { limit: "10", page:"1", status:"approved" }
with query-string package:
import qs from "query-string";
const obj = qs.parse(this.props.location.search);
console.log(obj.param); // { limit: "10", page:"1", status:"approved" }
no package:
const converttoobject = (url) => {
const arr = url.slice(1).split(/&|=/); // remove the "?", "&" and "="
let params = {};
for(let i = 0; i < arr.length; i += 2){
const key = arr[i], value = arr[i + 1];
params[key] = value ; // build the object = { limit: "10", page:"1", status:"approved" }
}
return params;
};
const uri = this.props.location.search; // "?status=approved&page=1&limit=20"
const obj = converttoobject(uri);
console.log(obj); // { limit: "10", page:"1", status:"approved" }
// obj.status
// obj.page
// obj.limit
hope that helps :)
happy coding!
score:14
"react-router-dom": "^5.0.0",
you do not need to add any additional module, just in your component that has a url address like this:
http://localhost:3000/#/?authority'
you can try the following simple code:
const search =this.props.location.search;
const params = new urlsearchparams(search);
const authority = params.get('authority'); //
score:17
update 2017.12.25
"react-router-dom": "^4.2.2"
url like
browserhistory
: http://localhost:3000/demo-7/detail/2?sort=name
hashhistory
: http://localhost:3000/demo-7/#/detail/2?sort=name
with query-string dependency:
this.id = props.match.params.id;
this.searchobj = querystring.parse(props.location.search);
this.from = props.location.state.from;
console.log(this.id, this.searchobj, this.from);
results:
2 {sort: "name"} home
"react-router": "^2.4.1"
url like http://localhost:8080/react-router01/1?name=novaline&age=26
const queryparams = this.props.location.query;
queryparams is a object contains the query params: {name: novaline, age: 26}
score:59
old (pre v4):
writing in es6 and using react 0.14.6 / react-router 2.0.0-rc5. i use this command to lookup the query params in my components:
this.props.location.query
it creates a hash of all available query params in the url.
update (react router v4+):
this.props.location.query in react router 4 has been removed (currently using v4.1.1) more about the issue here: https://github.com/reacttraining/react-router/issues/4410
looks like they want you to use your own method to parse the query params, currently using this library to fill the gap: https://github.com/sindresorhus/query-string
score:62
the above answers won't work in react-router v4
. here's what i did to solve the problem -
first install query-string which will be required for parsing.
npm install -save query-string
now in the routed component you can access the un-parsed query string like this
this.props.location.search
you can cross check it by logging in the console.
finally parse to access the query parameters
const querystring = require('query-string');
var parsed = querystring.parse(this.props.location.search);
console.log(parsed.param); // replace param with your own
so if query is like ?hello=world
console.log(parsed.hello)
will log world
Source: stackoverflow.com
Related Query
- Getting query parameters from react-router hash fragment
- Getting error when try to use React Router v6: Attempted import error: 'Action' is not exported from 'history'
- React query mutation: getting the response from the server with onError callback when the API call fails
- Why does React Router v6 seem unable to remove query string param from URL?
- Removing Hash from react router when using with Laravel
- React router private route not getting props from state (e.g. authentication state)
- Remove # Hash from URL in React with React Router
- How to access component parameters from app.js in react router
- Select item from array with React Router v4 query string
- react router 4 query parameters example not working
- React Router not getting data from request like path="/products?category=:category"
- Adding query parameters on form submission - React router 4
- React Router - Build State from Query String
- when I try to destructing the data from react query I am getting Property 'data' does not exist on type 'void'
- How to Use URL Parameters and Query Strings With React Router
- React router not getting query params
- Can't get query parameter after changing from Router to HashRouter on React JS
- How to query from mongo db in react based on URL parameters
- React - getting a component from a DOM element for debugging
- Getting DOM node from React child element
- How to redirect from axios interceptor with react Router V4?
- Accessing Redux Store from routes set up via React Router
- React router - Update URL hash without re-rendering page
- React Hooks - How to get parameter value from query string
- React Router v4 - Redirect to same route with different query params
- Moving from react router 3.x to 4.x
- React Router - How to replace dynamically parameters in a string
- In react router v4 how does one link to a fragment identifier?
- How to parse a query string in React Router
- How to pass the match when using render in Route component from react router (v4)
More Query from same tag
- Problem with a Cast using Router.put with mongoDB in MERN app
- Django foreign keys queryset displayed in react-redux
- How to show/hide spinners, snackbars, or other transient components with React Function Components
- Is Component inside render function called child component
- Babel register tutorial is not working
- Next.js: Error 413 Request Entity Too Large on file upload
- Understand take effect in redux saga work?
- React app route not working after deployed to IIS
- React - render component when clicking on a component which is not its child
- React Slick slickSetOption
- Re-render component when state changes in ReactJS
- Unable to get form values in React-Bootstrap's Formgroup Component
- How to set React to production mode when using Gulp
- Loading data from Firebase real time database to React hook component
- How to increase min-width in ".MuiSelect-select" in material ui Textfield with Select attribute also how to access Selectfield with Input adornment
- Victory chart - layout issue
- React/Javascript - Function returns before finished executing
- ReactJS: Tailwind override global CSS inline
- How to save data to array axios?
- Convert TypeOrm entities to react friendly Typescript DTO
- Next.js - no data in component when navigating from other route
- Display a 1 GB video file in react js frontend, stored in private S3 bucket using flask
- Merge two JSON data into one with particular key values
- How use :hover in :last-child in material-ui?
- setting state with onChange in React results in canvas being null
- React <Switch> is not getting updated or changing its state
- Generate a json list by parsing a list
- React - toggle class: useState hook form several button
- Twillio Script tags in React component
- How can I put a background image on a circle component?