In my previous article, we have seen how values can be passed through from one component to the other. Then, I mentioned about using query strings as another option which we can pass a value or values via URL. I wondered what if...what if we have a handling of the query strings in React.
As I search through NPM and...voila! There it is!
URL Source: npmjs.com/package/query-string
Go back to VS Code Terminal and type in the command
npm install query-string --save before we proceed further.
Next, I will be using
react-router-dom in the meantime to traverse/switch to other components.
NOTE: How I use and setup the
react-router-dom will be discussed in another article, no worries hehehe 😁😁😁
Now that we have installed and setup these two packages, in our Navbar.js, let say we want to pass a value, or any value rather in Features component. You will notice that there is a property
to in Link object/component:
I want to pass 2 keys and 2 values. To do this, at the end of the URL we add a question mark (?) to separate between the actual URL and query strings
Let us go back to our React application and before you click "Features", when you hover your mouse over the "Features" link, you will notice on you lower-left of your browser you will see the full URL + the query strings that we are trying to pass on to the other component:
How do we now extract the data we pass through? Going back to our VS Code and open Features.js. On the first curly brace, click Enter a few times and type in the following function:
In addition, add a button with the onClick event so that it will call on the function we have created:
You may be wondering what does the function do? The function we have created will search and parse through the URL and will return a string or strings. We declared a variable named
qs (short for query string) to hold the query strings that we have extracted from the URL, followed by an
alert() function for us to see the key items we need:
On the other hand, the button we have created will call on the function
getQueryStrings() through the onClick property.
To test this we have:
NOTE: If you want to secure the data you will be passing, you can encrypt first the data from the origin component then, make sure the destination component has a decrypt function with it.
And there you go! 😁It is up to you on how you will pass data from one component to the other. It will really depend on your requirements on how to use these.
Again, kudos! and happy coding! ✌️😁