next.jsnext-link

How to use next link href with condition


I have this code :

<a
  onClick={() => {
    if (fortype === "user") {
      if (rd.track !== null) {
        router.push({
          pathname: `/tracks/${rd.track._id}`,
          query: {
            from: router.asPath,
            at: page,
          },
        });
      }
    } else {
      if (rd.owner !== null) {
        router.push({
          pathname: `/users/${rd.owner._id}`,
          query: {
            from: router.asPath,
            at: page,
          },
        });
      }
    }
  }}
>
  My link
</a>

I am trying to replace the <a> tag with next/link but it gives me this error:

Error: Failed prop type: The prop href expects a string or object in <Link>, but got function instead. Open your browser's console to view the Component stack trace.

I tried doing it like this :

import Link from "next/link";

<Link
  href={() => {
    if (fortype === "user") {
      if (rd.track !== null) {
        return {
          pathname: `/tracks/${rd.track._id}`,
          query: {
            from: router.asPath,
            at: page,
          },
        };
      }
    } else {
      if (rd.owner !== null) {
        return {
          pathname: `/users/${rd.owner._id}`,
          query: {
            from: router.asPath,
            at: page,
          },
        };
      }
    }
  }}
>
  My link
</Link>

Solution

  • Your logic is right but the <Link> component does not accept functions,
    However if you declare a function then pass its result to href it will work:

    const myFunction = () => {
    //...
    }
    

    This works because here you are passing the result of a function which is an object, not a function.

    <Link
      href={myFunction()}
    >
    My link
    </Linl>