Getting URL Parameters on GatsbyJS
Use props.location
, introduced in Gatsby v2. It's made available by @reach/router to all components via props
.
function Component(props) {
// use props.location...
return ...
}
Use URLSearchParams.get()
as described on MDN:
// Get the location object that is implicitly passed as props
// for every page in the `pages` folder
const Index = ({ location }) => {
console.log(location); // inspect location for yourself
// the parameter to return for URL. Example:
// https://localhost:8000/?parameter1=firstParam¶meter2=secondParam
const params = new URLSearchParams(location.search);
const parameter1 = params.get("parameter1");
const parameter2 = params.get("parameter2");
console.log(parameter1); // -> "firstParam"
console.log(parameter2); // -> "secondParam"
// ...
Alternative: package query-string
yarn add query-string
or npm i --save query-string
import * as queryString from "query-string";
// Get the location object that is implicitly passed as props
// for every page in the `pages` folder
const Index = ({ location }) => {
console.log(location); // inspect location for yourself
// query-string parses the parameters that are contained in the location object
const { parameter1, parameter2 } = queryString.parse(location.search);
console.log(parameter1);
console.log(parameter2);
// ...