NextJs / View / Data passing between pages
Data passing between pages
-
1. Files
Option 1: using URL parameters
import { useRouter } from 'next/router'; function Product() { const router = useRouter(); const { id } = router.query; return Product: {id}
; } function Home() { return ( <> Product 1 Product 2 > ); }Option 2: pass object data
import Link from 'next/link'; function MyComponent() { return ( Go to User ); } import { useRouter } from 'next/router'; function User() { const router = useRouter(); const { name, age } = router.query; return ( Name: {name}); }
Age: {age}option 3: without query string
1. create a component /components/AppContext.tsx
2. /pages/_app.tsximport { createContext } from "react"; const AppContext = createContext(); export default AppContext;
3. Share state between pagesimport '../styles/globals.css' import { useState } from 'react'; import AppContext from '../components/AppContext'; function MyApp({ Component, pageProps }) { const [session, setSession] = useState() return ( ) } export default MyApppage1.tsx
import AppContext from "../components/AppContext" import { useContext, useState } from "react" import { useRouter } from "next/router"; export default function Page1() { const [value, setValue] = useState() const context = useContext(AppContext) const router = useRouter() return ( setValue(event.target.value)} /> page2.tsx
Outputimport { useContext } from "react" import AppContext from "../components/AppContext" export default function Page2() { const context = useContext(AppContext) return ( {context.session}) }page 1
page2