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
Based on what are trying to achieve
I created a file named [property1]&[property2].js in the root of pages folder.
[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
- Rename the file
[property1]&[property2].js
to index.js
(assuming that it on the root path /)
- Now you can pass the query params to the url example:
/?property1=value1&property2=value2
- Access these query params in your comppnent using the useSearchParams hook
useSearchParams is a Client Component hook that lets you read the current URL's query string.
import { useSearchParams } from 'next/navigation';
export default function SearchBar() {
const searchParams = useSearchParams();
const search = searchParams.get('search');
// URL -> `/dashboard?search=my-project`
// `search` -> 'my-project'
return (
<>Search: {search}</>
);
}
Example
// index.js
import { useSearchParams } from 'next/navigation';
const Component = () => {
const searchParams = useSearchParams();
const property1 = searchParams.get('property1');
const property2 = searchParams.get('property2');
console.log(property1); // value1
console.log( property2); // value1
return (
<div>
HELLO WORLD
</div>
);
};
export default Component ;
Using the useRouter
hook
You can Also use the useRouter
hook to access the query params in your component:
const Component = () => {
const router = useRouter();
const { property1, property2 } = router.query;
console.log(property1); // value1
console.log(property2); // value2
return (
<div>
HELLO WORLD
</div>
);
};
export default Component;
EDIT
I think you misunderstood how to use dynamic routing in Next.js. If you want to make property1
and property2
mandatory in order to access the page you need to have a url that's look like this /[property1]/[property2]
where property1
is a folder on the pages
that contains a js file named property2.js
. then you can access their value by using
// file pages/[property1]/[property2].js
import {useRouter} from "next/router";
export default function IndexPage() {
const router = useRouter();
const { property1, property2 } = router.query;
return (
<div>
<p>
property1: {property1} <br />
property2: {property2}
</p>
</div>
);
}
