In Next.js, using router.query allows you to retrieve URL query parameters, but the retrieved values are strings by default. If you need to convert these parameters to numbers, you can use several common JavaScript methods for conversion.
Here is a specific example to illustrate how to convert parameters from router.query to numbers:
Suppose our URL is http://localhost:3000/product?id=123. We need to retrieve the id parameter and convert it to a number.
First, import the useRouter hook and use it to access router.query:
javascriptimport { useRouter } from 'next/router'; function ProductPage() { const router = useRouter(); const query = router.query; // Retrieve the id parameter, which is currently a string const idStr = query.id; // Convert the string to a number let idNum = parseInt(idStr, 10); // Using parseInt with base 10 // Check if the conversion was successful; if idStr cannot be converted to a number, idNum will be NaN if (isNaN(idNum)) { console.error('The id query parameter is not a valid number'); idNum = null; // Or set to a default value or handle appropriately } return ( <div> <h1>Product ID: {idNum}</h1> {/* Use idNum for further operations */} </div> ); }
In this example, the parseInt() function is used to convert the string to an integer. The second parameter 10 specifies the radix (base 10). We also include error handling to ensure that when the id parameter is not a valid number, an error is logged and appropriate handling is performed.
Additionally, if you expect the parameter to be a floating-point number, you should use parseFloat() instead of parseInt().
javascriptlet idNum = parseFloat(idStr);
This conversion method is applicable to all scenarios where you need to retrieve numbers from URL query parameters for processing. It is commonly used during development, especially when dealing with applications that have dynamic routes and query parameters.