How to get or set the query string using React or Gatsby (without using document or window objects):
https://link.com/?color=#fff&theme=light
CodePudding user response:
you can use this module for react
:
https://github.com/pbeshai/use-query-params
for gatsby
, you can use this plugin :
https://www.gatsbyjs.com/plugins/gatsby-plugin-use-query-params/
it'll wrap your app with QueryParamProvider
CodePudding user response:
Since Gatsby has an SSR (Server-Side Rendering) part, you can't access directly the window
or other global objects (such as document
) because at the time you might be requesting them, they may be not available.
So, to get the URL parameters, the straightest forward solution is to use a useEffect
with empty dependencies ([]
), a function that will be triggered once the DOM tree is loaded (when window
should be available).
const SomePage = () => {
const [color, setColor]=useState('');
const [theme, setTheme]=useState('');
useEffect(()=>{
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
setColor(urlParams.get('color'))
setTheme(urlParams.get('theme'))
}, [])
return <section><h1>The color is {color} and the theme is {theme}</h1></section>
}
Being a delayed triggered function (it will be fired only one time and once the DOM tree is loaded) window
should be available. If the code breaks, wrap the window
manipulation inside the following condition:
if (typeof window !== 'undefined'){}
To set the value the approach is exactly the same using set
(from URLSearchParams
)