Sling Academy
Home/Next.js/Passing data via a Link component in Next.js

Passing data via a Link component in Next.js

Last updated: January 09, 2023

This concise article is about passing and retrieving data with Link components in Next.js. We’ll discuss the technique (just a few words) and then examine a complete example of applying that technique in practice.

Overview

You can pass a data object via a Link component like so:

<Link
          href={{
            pathname: "/some-page",
            query: data, // the data
          }}
>
         Some Text
</Link>

To retrieve the passed data, we can use the useRouter hook like this:

const router = useRouter();
const data = router.query;
console.log(data);

For more clarity, see the example below.

The Example

App Preview

The sample Next.js app we are going to build has two routes:

  • /: Home
  • /some-page: SomePage

On the home page, there are a Link and a text input. The Link is used to navigate to SomePage. The user can enter a name (or whatever they want) into the text field. The entered text will be passed to SomePage through the Link.

A short demo is worth more than a thousand words:

The Code

1. Create a brand new Next.js project:

npx create-next-app example

2. Remove all of the default code in pages/index.js and add the following:

// index.js
import Link from 'next/link';
import { useState } from 'react';

export default function Home() {
  // this data will be passed to /some-page via the Link component
  const [data, setData] = useState({ name: '' });

  return (
    <div style={{ padding: 40 }}>
      <h1>Sling Academy</h1>

      <div>
        {/* This text field is used to create dynamic data */}
        <input
          type='text'
          placeholder='Enter a name here'
          value={data.name}
          onChange={(event) =>
            setData({
              name: event.target.value,
            })
          }
        />
      </div>

      <p>
        {/* Here is the Link */}
        <Link
          href={{
            pathname: '/some-page',
            query: data, // the data
          }}
          style={{ color: 'blue', textDecoration: 'underline' }}
        >
          Go to SomePage
        </Link>
      </p>
    </div>
  );
}

3. In your /pages directory, create a new file named some-page.js and add the code below:

// some-page.js
import { useRouter } from "next/router";

export default function SomePage() {
  const router = useRouter();
  const query = router.query;
  const name = query.name;

  return (
    <div style={{ padding: 40 }}>
      <h1>SomePage</h1>
      <h2>
        Name: <span style={{ color: "red" }}>{name}</span>
      </h2>
    </div>
  );
}

4. Run the app and go to http://localhost:3000 to check the result:

npm run dev

That’s it. Happy coding!

Next Article: Next.js: Extracting URL params inside getStaticProps function

Previous Article: Next.js: Fetching Data in Server Components

Series: Fetching and Rendering Data in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported