SPFx Basics: How to get a query string value
Posted
Tuesday, September 11, 2018 9:03 AM
by
CoreyRoth
Contrary to popular belief, I still do development. In fact, I do quite a bit of development. In the last couple of years, I have built two mobile platforms as a service using Ionic and Angular. This node.js based development stack positioned me well to start working with SPFx. I'm starting up a string of blog posts that help cover the basics that I think that we often overlook in the bigger picture of how to do things with SPFx. Today's topic is simple: reading a value from the query string. When I recently looked at this simple scenario, I thought sure I could go back to my JavaScript roots and use location.href but there has to be a better way now right? The SPFx team thought of that and they included a nice helper class to get you going called UrlQueryParameterCollection.
Start by including a reference to UrlQueryParameterCollection.
import { UrlQueryParameterCollection } from '@microsoft/sp-core-library';
We use the getValue() Like ASP.NET or other languages, you'll usually want to check to see if it has a value before using it. I then cast it to an integer time after reading the value.
if (queryParameters.getValue('id')) {
id = parseInt(queryParameters.getValue('id'));
}
Again, this is a simple example, but hopefully it will keep you from going down the path with location.href. The sp-core-library has all sorts of useful utitlities for you to use such as Environment, Random Number Generators, and logging. Check it out the next time you start out a project.