27

I am stuck with a problem with passing data from one page to another page in next.js as I am building a basic news application in which I am fetching get requests from news api and I got results of 10 articles and I mapped them correctly but I want to pass the single article date to a new Page named singleNews. So How can I do it? here is place where I am fetching all 10 articles:

export default function news({data}) {
    // const randomNumber = (rangeLast) => {
    //   return  Math.floor(Math.random()*rangeLast)
    // }
    // console.log(data)

    return (
        <>
        <div>
            <h1 className="heading">Top Techcrunch Headlines!</h1>
        </div>
        <div className={styles.newsPage}>
            { // here you always have to check if the array exist by optional chaining
             data.articles?.map(
                (current, index) => {
                    return(
                        <Card datas={current} key={index+current.author} imageSrc={current.urlToImage} title={current.title} author={current.author}/>
                    )
                }
            )
        }
        </div>
        </>
    )
}

export async function getStaticProps() {
    const response = await fetch(`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${process.env.NEWS_API_KEY}&pageSize=12`)
    const data = await response.json() // by default Article length is 104
    // const articles =  data.articles;

    return{
        props : {
            data,
        }
    }
}
juliomalves
  • 42,130
  • 20
  • 150
  • 146
Mohit Ashliya
  • 403
  • 1
  • 4
  • 7

1 Answers1

46

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;

Update - Next.js v13:

Some changes have been made on this version. 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.

Previous to v13.4.1, the app directory feature can be enabled under the experimental flag on next.config.js file:

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: {
    appDir: true
  }
}

module.exports = nextConfig

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.

ivanatias
  • 3,105
  • 2
  • 14
  • 25