NextJS: how to Link to new page with current page slugs?

Viewed 2204

I currently have a url like this:

http://localhost:3000/courses/italian/dynamic/lessons/wenC6hgETeMHSiFNabvk http://localhost:3000/courses/[language]/dynamic/lessons/[lessonID]

I am trying to find an easy way to reach the following .../exercises page. All I need to do is add /exercises to the end of the above url. However, the following solution didn't work. Evidently, <Link /> no longer remembers what the [language] or [lessonID] params are on my current page.

<Link href={`exercises/flashcards`} passHref>
   <a>begin</a>
</Link>

error message: screenshot of error message

At this moment, the only solution I can think of is rewriting the entire URL with the needed slugs and passing that into href, but that feels a bit unnecessary if all I need to do is concat what I already have with /exercises/flashcards.

Am I missing something?

2 Answers

You don't necessarily need to pass the params down as props, you can use useRouter to get the current path then add the extra bits to it in the Link's href.

import { useRouter } from 'next/router';

export default function SomePage() {
    const { asPath } = useRouter();

    return (
        <Link href={`${asPath}/exercises/flashcards`}>
            <a>begin</a>
        </Link>
    )
}

In the event that nobody answers, here is the solution using my current slugs.

// using this nextjs function to pass the params of my url as a prop for SSR.
export async function getServerSideProps({ params }) {
  const { language, lessonID } = params;
  const data = await fetchLesson(language, lessonID);

  if (!data) {
    return {
      notFound: true,
    };
  }

  return {
    props: { data, params }, // will be passed to the page component as props
  };
}

---

// using those above param props within this Link on my component.
<Link
   href={`/courses/${props.params.language}/dynamic/lessons/${props.params.lessonID}/exercises/flashcards`}
   passHref
>
  <a>begin</a>
</Link>
Related