I am trying to create a route that looks like this /property1=value1&property2=value2
and then I need to access the values of property1
and property2
. I created a file named [property1]&[property2].js
in the root of pages
folder.
I am trying to access the component via the following link http://localhost:3000/property1=value1&property2=value2
//[property1]&[property2].js
import { useRouter } from "next/router";
const Component = () => {
const router = useRouter();
return (
<div>
HELLO WORLD
</div>
);
};
export default Component ;
I tried to test the content of router.query
and obtained following output.
console.log(router.query);
//outputs { property1]&[property2: "property1=value1&property2=value2" }
I am using the next.js version 13.3.1
and for the moment I don’t prefer to use the experimental apps
directory as per docs. So any solutions to achieve this task via pages
directory would be most preferred for now.
2
Answers
You should be able to do this
See docs
Based on what are trying to achieve
[property1]&[property2].js
is not the best way to do it.If i’m not getting it wrong, you want to pass search params in the url and access them in your component here on the route ‘/’.
How to proceed ?
NextJs 13 new
useSearchParams
hook API[property1]&[property2].js
toindex.js
(assuming that it on the root path /)/?property1=value1&property2=value2
Example
Using the
useRouter
hookYou can Also use the
useRouter
hook to access the query params in your component:EDIT
I think you misunderstood how to use dynamic routing in Next.js. If you want to make
property1
andproperty2
mandatory in order to access the page you need to have a url that’s look like this/[property1]/[property2]
whereproperty1
is a folder on thepages
that contains a js file namedproperty2.js
. then you can access their value by using