I’m learning nextjs using book "Building React Apps using server-side rendering"
In this I’m building basic react app with index page link to about page.
The project package.json
–
{
"name": "my-next-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "next",
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"next": "^13.4.19",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
pages/index.js
is –
import React from "react";
import GetLink from "../sharedComponents/DynamicRouter";
function MyComponent() {
return (
<div>
<p>Hello from Next.js</p>
<GetLink title='Page 1'></GetLink>
<GetLink title='Page 2'></GetLink>
<GetLink title='Page 3'></GetLink>
</div>
);
};
export default MyComponent;
sharedComponents/DynamicRouter.js
is –
import React from "react";
import Link from "next/link";
function GetLink(props) {
return (
<div>
<Link href={`/SecondPage?content=${props.title}`}>{props.title}</Link>
</div>
);
}
pages/SecondPage.js
is –
export default (props) => {
console.log(JSON.stringify(props));
return (
<h1>
Welcome to {props.url.query.content}
</h1>
)};
The console.log
prints {}
in the console.
In the browser I’m getting error.
What I would like to see is Welcome to Page 1
.
Any idea how to fix this?
2
Answers
Your
pages/SecondPage.js
is incorrect, because you are not receiving anyprops
to it (which is why theconsole.log
is{}
). Soprops.url
isundefined
. Hence the error you are seeing.If your use-case to display the
content
query param, you can do like this:Its just that you are confused with terms, let me explain
params
These are of type
route/:id
=> Hereid
is paramsearchParams
These are of type
route?id
=> Here id is searchParamparam
&searchParams
These includes both
route/:id1?id2
=> Here id1 is param & id2 is searchParam“
So basically what you are trying to do is, pass
searchParam
and looking forparam
Solution ,
params
searchParam
To further understand follow the below links
Also refer latest Nextjs 13 code templates
Next.js 13+ Power Snippets | TypeScript/Javascript
It includes wide range of code snippets for both
ts
andjs
. Find all snippets here