skip to Main Content

Please help, I need to get data from an array of a page, then display it on another page.
I’m, using NextJs, with Typescript, AppRoute
Here’s my code:

app/page.tsx:

import Image from 'next/image'
import Link from 'next/link'

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

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

app/Detail/page.tsx

import HomePage from "../page";

export default function Detail() {
    return (
        <>
            <h1> 
                This is detail page of {HomePage.listMember.name}
            </h1>
        </>
    )
}

I have tried to use route but not working

2

Answers


  1. Change to

    export const listMember = [...
    ...
    
    import {listMember } from "../page";
    
    export default function Detail() {
        return (
            <>
                <h1> 
                    This is detail page of {listMember.name}
                </h1>
            </>
        )
    }
    
    Login or Signup to reply.
  2. You need to export the list from your main page

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

    and then access the query param from the detail page and find the param like this:

    import { useRouter } from 'next/router';
    import HomePage,{listMember} from "../page";
    
    export default function Detail() {
    const router = useRouter();
    const { name } = router.query;
    
      const member = listMember.find(member => member.name === name);
    
        return (
            <>
                <h1> 
                    This is detail page of {member?.name}
                </h1>
            </>
        )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search