pass id through Link in next js with out effecting the url

Viewed 284

I have a set of alert components and each alert component opens a new page with a dynamic url based on itm.Name

I also want to pass itm.id or all the fields in itm to the [qst] component and access the itm.id there with out affecting the current url

How can I do that?

<div className="question">
            {data.map((itm) => (
              <Link
                key={itm._id}
                href={{
                  pathname: "question/[qst]",
                }}
                as={`/${encodeURIComponent(itm.Name)}`}
              >
                <Alert className="question">{itm.Name}</Alert>
              </Link>
            ))}
          </div>

getseverside


export async function getServerSideProps({ query }) {
  var id1 = query;

  console.log(id1);
  const queryRequest = fetch("https://askover.wixten.com/questone/" + id1).then(
    async (res) => await res.json()
  );


1 Answers

You can pass query params to your route and get them in your dynamic route component with useRouter

    <div className="question">
        {data.map((itm) => (
            <Link
                key={itm._id}
                href={{
                  pathname: `question/[qst]`,
                  query: { id: itm._id }
                }}
            >
                <Alert className="question">{itm.Name}</Alert>
            </Link>
        ))}
    </div>

    import { useRouter } from 'next/router'

    const Qst = () => {
      const router = useRouter()
      const { id } = router.query

      return <p>id: {id}</p>
    }

    export default Qst
Related