Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Typescript and App Router. I attempted to use { useRouter } from "next/router", but it's deprecated in my version. Currently, I'm using { useParams } from "next/navigation", but I'm unsure how to implement it. Please assist me!

Below is my code: app/page.tsx:

'use client'

import Link from "next/link";
import Heading from "../Components/Heading";
import { data } from "autoprefixer";
import Router from "next/router";
import { send } from "process";
import type { NextPage } from "next";

export default function HomePage() {
  return (
    <>
      <Heading>iOS Team</Heading>
      <ul className="px-5">
        {iOS.map(member =>
          <li>
            <Link
              href={{
                pathname: "/Detail",
                query: member
              }}>{member.account}</Link>
          </li>
        )}
      </ul>
    </>
  )
}

List of members:

export const listMember = [
  {
    id: 1,
    name: "name1",
    age: 20,
  },
    {
    id: 2,
    name: "name2",
    age: 18,
  },
    {
    id: 3,
    name: "name3",
    age: 2,
  }
]

Detail screen:

'use client'

import HomePage,{ listMember } from "../page";
import { useParams } from "next/navigation";
import { useRouter } from 'next/router';

export default function DetailMember() {

    const params = useParams();
    const member = listMember.find((item) => item.id === parseInt(params.id));
    console.log(params)

    return (
        <>
        <h1>
        This is detail page of {member?.account}
        </h1>
        </>
    )
}

I tried using "useParams" but it didn't work.

Answer №1

When you passed your member object as "query" in the <Link/> component, it is recommended to use useSearchParams instead. This will allow you to access the query string easily.

const searchParams = useSearchParams();
const memberId = searchParams.get('id');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences in the rendering of SVG feDiffuseLighting between Chrome and Firefox

Hey there! I encountered a strange issue with my next.js project. It has a default config and includes an SVG filter. <svg xmlns="http://www.w3.org/2000/svg"> <filter id='roughpaper'> <feTurbulence type=" ...

Tips for showcasing images from (block content) that is rich text using portable text

What is the method for showing images from (block content) rich text in portable text using Sanity as backend and Next.js as frontend? This is how my portable text appears: <PortableText value={blog.body} /> No variables or constants are connected ...

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

Having trouble grasping the concept of Interfaces and dealing with FormGroup problems in Angular?

Apologies if my question is a duplicate, I have found several solutions for the same issue on Stack Overflow, but unfortunately, I struggle to understand them in technical terms. Problem 1 src/app/models/dataModel.ts:2:5 2 id: number; ~~ The exp ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

A guide to using Angular to emphasize text based on specific conditions met

Currently, I am developing a testing application that requires users to choose radio type values for each question. The goal is to compare the selected answers with the correct answers stored in a JSON file. To achieve this, I have implemented an if-else ...

Tips for retrieving and presenting information from a JSON document in a React TypeScript application

I am struggling to display data in a list format using TypeScript. I am able to fetch the data but unable to display it properly. I am currently using map to iterate through an array of JSON objects. //json file [ { "id": "6s", ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

Getting a specific array from the API with fetch in Angular: A step-by-step guide

I am trying to retrieve images from an API, but I'm having trouble accessing all the arrays to get to the data. Currently, I am only able to fetch the posts arrays in a single call and not beyond that. https://i.stack.imgur.com/aFWlD.jpg My method fo ...

What could be causing useEffect(()={...},[]) to not trigger on component rendering?

Regarding the useEffect() function and its behavior upon initial page render, there are several questions. Even after confirming that my code is correct with regards to the parameters passed to useEffect, I am still facing the same issue. useEffect(() => ...

Implement handleTextChange into React Native Elements custom search bar component

I need help with passing the handleTextChange function in the SearchBarCustom component. When I try to remove onChangeText={setValue} and add onchange={handleTextChange}, I am unable to type anything in the search bar. How can I successfully pass in the ...

Nearly every category except for one from "any" (all varieties but one)

In Typescript, is it feasible to specify a type for a variable where the values can be any value except for one (or any other number of values)? For instance: let variable: NOT<any, 'number'> This variable can hold any type of value excep ...

How can I close the Headless UI modal (dialog component) by clicking on its children?

Is it possible to close a modal window by clicking on any child link? import { Dialog } from "@headlessui/react" const [modalIsOpen, setModalIsOpen] = useState<boolean>(false) <Dialog open={modalIsOpen} onClose={() => setModalIsOpen ...

Tips on troubleshooting the issue when attempting to use a hook in your code

I am trying to implement a hook to manage the states and event functions of my menus. However, when I try to import the click function in this component, I encounter the following error: "No overload matches this call. The first of two overloads, '(p ...

Remove buttons from carousel elements in React Multi-Carousel

Is there a way to hide the arrows in the react-multi-carousel component? https://i.stack.imgur.com/V1nix.png ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

In TypeScript, how are angle brackets like methodName<string>() utilized?

Could someone please assist me in understanding why we use angular brackets <> in typescript? For example, I have provided some code below and would appreciate an explanation. export class HomePage { constructor(public navCtrl: NavController) { ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

The 'picker' property is not found in the '{}' type but is necessary in the 'TimeRangePickerProps' type

I am encountering an issue while trying to implement the new RangePicker for the TimePicker of antd v4. Surprisingly, this error only occurs in my development environment and not when I try to reproduce it on codesandbox. Despite checking their documentati ...