how to pass data from one page to another page in Next.js?

You can pass data to another page via Link component this way:

import Link from 'next/link'

<Link
  href={{
    pathname: '/to-your-other-page',
    query: data // the data
  }}
>
  <a>Some text</a>   
</Link>

and then receive that data in your other page using router:

import { useRouter } from 'next/router'
const router = useRouter();
const data = router.query;

This is also known as putting state in the URL.

Update – Next.js v13+:

Next.js added a new app directory feature which uses React Server Components by default. Since Next.js v13.4.1 the app directory is now stable and is the recommended way of working with the framework.

Some changes have been implemented on the Link component and useRouter hook. Also, some new hooks have been added for client-side use. A brief list of these changes:

  • It’s no longer needed to wrap an a tag with the Link component. The new Link component extends the HTML <a> element. <a> tag attributes can be added to Link as props. For example, className or target="_blank". These will be forwarded to the underlying <a> element on render.

  • The new useRouter hook should be imported from next/navigation and not next/router.

  • The query object has been removed and is replaced by useSearchParams().

Passing data from one page to another using app directory feature and Server Components:

import Link from 'next/link'

const SomePage = () => {
  return (
    <section>
      <h1>Some page</h1>
      <Link
        href={{
          pathname: '/anotherpage',
          query: {
            search: 'search'
          }
        }}
      >
        Go to another page
      </Link>
    </section>
  )
}

export default SomePage

Receiving the data through searchParams prop:

const AnotherPage = ({ searchParams }) => {
  console.log(searchParams.search) // Logs "search"

  ...
}

export default AnotherPage

On Client Components:

'use client'

import { useSearchParams } from 'next/navigation'

const SomeClientComponent = () => {
  const searchParams = useSearchParams()
  console.log(searchParams.get('search')) // Logs "search"
 
  ...
}

export default SomeClientComponent

This also works with page components on pages folder. Don’t include the 'use client' directive in this case.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)