I have a set of alert components and each alert component opens a new page with a dynamic url based on itm.name
I also want to pass itm.id
or all the fields in itm
to the [qst]
component and access the itm.id
there with out affecting the current url
How can I do that?
<div className="question">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "question/[qst]",
}}
as={`/${encodeURIComponent(itm.Name)}`}
>
<Alert className="question">{itm.Name}</Alert>
</Link>
))}
</div>
getseverside
export async function getServerSideProps({ query }) {
var id1 = query;
console.log(id1);
const queryRequest = fetch("https://askover.wixten.com/questone/" id1).then(
async (res) => await res.json()
);
CodePudding user response:
You can pass query params to your route and get them in your dynamic route component with useRouter
<div className="question">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: `question/[qst]?id=${itm._id}`,
}}
as={`/${encodeURIComponent(itm.Name)}`}
>
<Alert className="question">{itm.Name}</Alert>
</Link>
))}
</div>
import { useRouter } from 'next/router'
const Qst = () => {
const router = useRouter()
const { id } = router.query
return <p>id: {id}</p>
}
export default Qst
CodePudding user response:
You need to pass unique id to link as slug -
<div className="question">
{data.map((itm) => (
<Link
key={itm._id}
href={{
pathname: "question/[qst]",
query: {qst: itm._id}
}}
as={`/${encodeURIComponent(itm.Name)}`}
>
<Alert className="question">{itm.Name}</Alert>
</Link>
))}
</div>
then in your [qst]
file, you will receive in server side like this:
export const getServerSideProps = ({query}) => {
const {qst} = query;
...
}
in client side:
const Qst = () => {
const router = useRouter();
const {qst} = router.query;
return <>{qst}</>
}