So I have a page with six Link tags which all need to redirect to one page with different props depending on which link is clicked. Here's how I'm passing props:
<Link href={{
pathname: '/products',
query: {category: 'Starters'}
}}>
<div class="container">
<div class="content">
<div class="content-overlay"></div>
<img class="content-image" src="/starters.png" />
<div class="content-details fadeIn-bottom">
<h3 class="content-title text-uppercase">Starters</h3>
</div>
</div>
<h3>Starters</h3>
</div>
</Link>
On the products page, here's how I'm reading these props:
export default function products(){
const router = useRouter()
const {id} = router.query
console.log(id)
return(
<>
<Navbar></Navbar>
<h1 className="text-center">{id}</h1>
<Footer></Footer>
</>
)
}
The problem here is that my id value is read as undefined or empty. I need to take this value, show it on my page and then send it to an API endpoint which will then use this string to execute a conditional SQL query.
Any idea as to why I'm getting an empty or undefined value and how to fix this?
Please try functional component instead like below. Hooks are used in functional components.
import React, { useState } from "react";
const Products = (props) => {
const [myId, setMyId] = useState<any>(null);
const [myCategory, setMyCategory] = useState<any>(null);
useEffect(() => {
console.log(props.router.query)
setMyId(props.router.query.id)
setMyCategory(props.router.query.category)
}, [props.router]);
return(<h1 className="text-center">{myId}</h1>);
}
Alternatively
import React, { useState } from "react";
import router from 'next/router';
const Products = () => {
const {id, category} = router.query
const [myId, setMyId] = useState<any>(null);
const [myCategory, setMyCategory] = useState<any>(null);
useEffect(() => {
if(!id) {
return;
}
console.log(id);
setMyId(id);
setMyCategory(category);
}, [id]);
return(<h1 className="text-center">{myId}</h1>);
}
Can you also modify your jsx a bit? For example
<Link href={{
pathname: '/products',
query: {id: 1, category: 'Starters'}
}}>
Starters
</Link>
<div class="container">
<div class="content">
<div class="content-overlay"></div>
<img class="content-image" src="/starters.png" />
<div class="content-details fadeIn-bottom">
<h3 class="content-title text-uppercase">Starters</h3>
</div>
</div>
</div>