简体   繁体   中英

how to pass object as params in Router.push() in nextjs and access that object in other component

Router.push({pathname: '/card', query:{data: ObjectData}})

I get query as empty value could not pass object into it

you can pass your params like this case:

router.push({
      pathname: '/card',
      query: { data: JSON.stringify(ObjectData)}
  })

and you can get params in card component like this:

JSON.parse(props.router.query.data);

Ciao, in next.js you can pass query parameters like this:

Router.push({
  pathname: '/card',
  query: { name: 'Someone' }
})

And you retrieve it this way:

this.props.router.query.name

Supposing that your ObjectData is a JSON object, you could pass it like:

Router.push({pathname: '/card', query: ObjectData})

This doesn't work for me. It says Cannot read property query of undefined

I have an object of userData which I want to pass from nav component to userprofilePage .

So, in nav I write:

onClick={() => {
  Router.push({
    pathname: "/userProfilePage",
    query: { data: JSON.stringify(userData) },
  });
}}

and to retrieve in userProfilePage :

const router = useRouter();
const userData = JSON.parse(props.router.query.data);

this how you pass object as parameter in nextjs

  router.push({
  pathname: "/biodata",
  query: { data: "test" },
  });

and if it is a variable eg id=12346

 router.push({
  pathname: "/biodata",
  query: { data: id },
  });

and you access that object in other component using these line of code

const router = useRouter();
const {
query: { data },
} = router;

ie how to used it in new page.about page

import { useRouter } from "next/router"
export default function AboutPage() {
const router = useRouter()
const {
query: { data },
} = router
return <div>About us: {data}</div>
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM