How to get url query parameter values in gatsby for any features like api calls or matching it with some data
So have you ever been stuck to get and access the url params from a search input in a gatsby site for any feature like matching or comparing or any kind of purpose? If you have ever been stuck on such an identical issue, this article is welcoming you with open arms.
So I am just giving you the following instructions and also sharing code snippets to achieve this in a simple way.
First of all install gatsbli cli globally with the below command with our best friend npm (you can also use yarn as well) by opening your command prompt or gitbash(on windows) or terminal(linux or macos)
npm install -g gatsby-cli
yarn add global gatsby-cli
Check your gatsby version, make sure it is the latest version in order to fix patches and get access to all new and latest features, use this command
gatsby --version
This should ideally return the version for gatsby on your terminal, if not then gatsbi-cli is still not yet properly installed.
See all the available commands with gatsby, just for your learning
gatsby --help
Run the following command from the command line. This will start up the interactive prompt to help you create a new Gatsby site.
gatsby new
These are the following interactive prompts in sequence. You can switch between options with your arrow keys and press enter to select any specific option.
Now stretch a bit, drink some water, take slow and deep breaths, till all the configurations that you have selected are taken into account and a fresh gatsby site is created. Just a note here, you can select other options as well other than the ones I have shown here as well and set up your project accordingly but for this article, I am using the simplest gatsby site.
Once done, navigate to your gatsby project directory using this command
cd my-first-gatsby-site
And now start the development server by using the following command from your gatsby project folder
gatsby develop
Once the server starts, visit localhost:8000 in your browser(most preferrably google chrome or mozilla firefox as these are most preferred for development experience with great development tools, like chrome dev tools in google chrome and also Firefox DeveloperTools in Firefox), as 8000 is the default port for the gatsby development server. It will look something like this below.
Awesome!! Now that you have come this far, open your gatsby project folder/directory in your favorite code editor(personally I like VS Code the most because of the awesome collection of extensions that makes lives easier and also so many different colors and themes to choose from). Now in order to get access to the url query parameters, you need react-router-dom package and a gatsby specific plugin by the name of gatsby-plugin-use-query-params.
So install these two dependencies and essential ingredients to achieve our goal. Here are the commands
npm install react-router-dom || yarn add react-router-dom
And for the gatsby-plugin-use-query-params
npm install use-query-params gatsby-plugin-use-query-params
|| yarn add use-query-params gatsby-plugin-use-query-params
Great now always remember whenever you install a plugin and intend to use it, you always have to add it to the plugins array in gatsby-config.js file like this.
module.exports = {
siteMetadata: {
siteUrl: `https://www.yourdomain.tld`,
},
plugins: [
"gatsby-plugin-use-query-params",
]
}
Great now that you have finished taking care of the package and the plugin, navigate to src/pages/index.js and use the below code snippet. Wait I will also explain but first the code base then the explanation. Don't forget to install es7+ react/redux/react-native snippets extension for a better experience and also don't forget to integrate emmet to be compatible with js, unless you are new to React ecosystem and want to code everything out.
src/pages/index.js
import React, { useState } from 'react';
import Search from '../components/Search';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
// styles
const headingStyles = {
marginTop: 0,
marginBottom: 64,
color: 'orange',
};
const searchInput = {
marginLeft: 300,
width: 200,
height: 50,
border: '1px solid #3987c9',
};
const buttonStyle = {
marginTop: 26,
color: 'white',
backgroundColor: 'black',
width: 200,
height: 30,
marginLeft: 300,
};
const handlesubmit = (e) => {
console.log(e.target.value);
};
// markup
const IndexPage = () => {
const [value, setValue] = React.useState('');
return (
<>
<h1 style={headingStyles}>Get url query parameters in a gatsby site</h1>
<form
action=""
onSubmit={(e) => {
handlesubmit(e);
}}
>
<input
style={searchInput}
name="s"
type="search"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
/>
<br />
<button style={buttonStyle} type="submit">
Submit
</button>
</form>
<Router>
<Routes>
<Route path="/" element={<Search />}></Route>
</Routes>
</Router>
</>
);
};
export default IndexPage;
So create a folder named components under src and create a file named Search.js under it. I will explain later why am creating this Search component. Here is the code for src/components/Search.js
import React from 'react';
import { useSearchParams } from 'react-router-dom';
const displayQueryParam = {
fontSize: 25,
fontWeight: 'bold',
color: 'indigo',
marginLeft: 300,
marginTop: 30,
};
const Search = () => {
const [searchParams, setSearchParams] = useSearchParams();
const searchKeyword = searchParams.get('s');
return (
<div style={displayQueryParam}>
This is your url query parameter: {searchKeyword}
</div>
);
};
export default Search;
So I will basically explain the points here what I have done here
I have created a form with an input type of search as it automatically generates url query parameters,and on the form submit, you can see the input value coming up in query parameters in url by "?s=whatever you typed in input field and after form submission".
Now our goal is to access and get this value and use it for any purpose, it can be for api calls, matching or comparing, anything you like.
So we use BrowserRouter,Routes and Route from react-router-dom package and use it to redirect to Search component as I want to access the url query param and show it in Search component but you can observe the path is same as "/" which is home itself. for this I am using
<Router>
<Routes>
<Route path="/" element={<Search />}></Route>
</Routes>
</Router>
- In Search component I am just using the useSearchParams hook to access the query parameter value. Here one thing that is important to note is you have to use tha same word as you have used in the name attribute. So the name attribute of input in index.js should match the word by which we are accessing it(here it is s as you can see below)
// src/pages/index.js
<input
style={searchInput}
name="s"
type="search"
value={value}
onChange={(e) => {
setValue(e.target.value);
}}
/>
// src/components/Search.js
const [searchParams, setSearchParams] = useSearchParams();
const searchKeyword = searchParams.get('s');
That's all!! So search for something and submit the form, you will see it appear on the page. The main objective is to capture the url query parameter and use it for any purpose whether it i a simple objective or a complex one.
Hope you enjoyed the article. This is my first one officially. I just like articulating thoughts and writing and expressing, and I feel writing articles is really great when you solve a problem or issue, and writing is like journal and a an awesome habit to cultivate to later revisit your ideas and thoughts and strategies. Hope you will also get a bit inspired from my blog.
Here's how it looks finally.
Here's the github link in case you want to try it out yourself.Clone it and feel free to explore it on your own. Textgithub.com/anutosh097/gatsby-url-query-par…
So I always like breaking down a complex problem into simpler parts, and accessing the url query params was one such simple part. Solved the simple part I was trying to do so, and ended up writing a blog on it, as I felt to express about it. Well accessing the url query parameter values can sometimes save you from delving into complex state management issues I feel. And always remember there are always multiple ways to solve one same problem, for instance you could have also used useState and localstorage to solve this same problem as well. So don't limit yourself from exploring and experimenting. Hope you will like the blog.