I'm trying to pass props to a new page in Next JS.
I'm mapping through an array, each item should link to a page where I can use data from the array as props:
{mentors.map((mentor) => (
<Link href="/developers/developer">
<div
key="name"
className="flex flex-col text-green-50 bg-gray-800 rounded-md p-6 gap-3 border border-gray-800 hover:border-gray-700 cursor-pointer"
>
<div className="flex justify-between items-center ">
<div className="flex items-center gap-2">
<img src={mentor.pic} className="rounded-full w-10" />{" "}
{mentor.name}
</div>
{mentor.timeZone}
</div>
<p className="text-gray-300">
I am a full-stack dev with over 8 years experience in
making software and web-apps.
</p>
<div className="flex gap-2 items-center">
Can teach:
{mentor.languages.map((language) => (
<p
key={language}
className="px-3 py-1 bg-gray-900 rounded-full max-w-max text-sm"
>
{language}
</p>
))}
</div>
</div>
</Link>
))}
This is the page:
export default function DeveloperPage({ name, picture }) {
return (
<>
{name}
<img src={picture}/> </>)}
I need to pass that {name} and {picture} prop from the item in the array to the new page. What's the most elegant way to do it in Next?
Thanks!
CodePudding user response:
You can pass it trough URL query
Like this
<Link href={`/developers/developer?name=${mentor.name}&picture=${mentor.picture}`}>
and you can use useRouter
on your DeveloperPage
to get its values
import { useRouter } from 'next/router'
export default function DeveloperPage() {
const router = useRouter()
const {name, picture} = router.query // <-- passed datas are in here
return (
<>
{name}
<img src={picture}/>
</>
)
}