Lex2000
Lex2000

Reputation: 229

How to make the Link href object work? (Next.js v12)

When I make the href as a string the link works, but when I make the href as an object, the link does not work. When I hover the link, I see link with the correct querystring. But it takes me to the first page.

// ProdCard

 type ProdProps = Pick<CardProps, 'background' | 'className'> & {
  name: string;
  prodNumber?: number;
  id: string;
};

export const ProdCard = ({ className, background, name, id, prodNumber = 0 }: ProdProps) => (
  <div className={className}>
    <Link
      href={{
        pathname: '/search',
        query: { page: 1, title: name, startDate,endDate, id },
      }}
      passHref
    >
      <a>
        <Card className={className} background={background}>
          <div>{name}</div>
          <div>{prodNumber}</div>
        </Card>
      </a>
    </Link>
  </div>
);

Link in code doesent work. But if i chenge it to this

href={`/search?title=${name}&startDate=${startDate}&endDate=${endDate}&prodId=${id}`}

it will work. How do I make an href work when it's set as object?

Upvotes: 1

Views: 809

Answers (1)

Marchy
Marchy

Reputation: 81

This should work as written and is most likely an issue with the page you are redirecting to. From what you posted, I don't see where startDate and endDate are defined. Are you redirecting to the first page if there are missing values?

I recreated it with this code:

import Link from 'next/link'

export default function Home(){
    const name='world'
    const startDate='2021-01-01'
    const endDate='2021-01-01'
    const id = 1;
    return (
        <div>
            <Link
      href={{
        pathname: '/params',
        query: { page: 1, title: name, startDate,endDate, id },
      }}
      passHref
    >
        <button>Search</button>
    </Link>
        </div>
    )
}

Hovered link

Upvotes: 1

Related Questions