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
- How can i validate input field in react using regular expression via hooks
- React on docker-compose: ERROR [3/6] COPY package.json ./
- Flux react, can an action get a store?
- Seeing empty page after deployed to S3 with React Route
- Can't input on other Form Fields
- Avoid code repetition - reactJs - javascript
- how to use a CDN inside a React component
- React/Nextjs - know what page is rendered on _app.js
- Using chart js options with react-chartjs-2 and typescript
- How can I combine child nodes with JSX?
- States For Login Page
- Text remains wrapped inside it's parent div - CSS, React
- How to use state as checked atribute in ReactJs?
- How to change a style of an HTML element in React?
- Using refs to modify an element in React.js
- TypeScript Error in React component on useState declaration and passing props to child component
- Prop sharing between components
- ReactJS - Proper way to get a result of dispatch
- Post call not placing headers in call. Axios
- How Do I Move a Component into a Different Div When Viewing on Mobile?
- Date validation issue
- How to fix no loaders are configured to process this file. See webpack.js web
- React Material-UI - styling displayed rows label in TablePagination component
- How to call a delete function with parameter(_id) outside the class in react js?
- Making an asynchronous call to an api doen't work through redux actions
- Buttons outside of carousel elements [react-multi-carousel]
- Why render props is not working with Curly Braces in render function?
- reactjs material-ui and redux form fields -- creating component
- using onClick with array map in Dynamic menu ( ReactJS)
- Form file accept type in ReactJS