Poornima Shinde
Poornima Shinde

Reputation: 179

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

Upvotes: 17

Views: 27129

Answers (4)

RaySun
RaySun

Reputation: 229

this how you pass object as parameter in nextjs

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

and if it is a variable e.g 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;

i.e 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>
} 

Upvotes: 0

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

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})

Upvotes: 4

Vaidehi S
Vaidehi S

Reputation: 1

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);

Upvotes: 0

Medisa
Medisa

Reputation: 409

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);

Upvotes: 27

Related Questions