Inside my data.js I have a 'product' array with the values 'name' and 'path' in it. The page address is referred to as 'path'
data.js
export const product = [{name:Processor, path:processor},
{name:Graphics Card, path:graphics-card}]
My Index page
index.js
-------------
import { product } from "data";
export default function Builder({ children }) {
return(
<>
<Navbar>
{product.map((item) => (
<li key={item.path}>
<Link href={`/products/${item.path}`} >
<a><span >{item.name}</span></a>
</Link>
</li>
))})
</Navbar>
{children}
</>
}
[product] is dynamically created page.
My folder structure
data.js
index.js
products/
[product].js
[product.js]
------------
import Builder from "./index"
export default function Product() {
return (
<>
<Builder>
//I need to display 'product-name' here.
</Builder>
</>
)
}
When I use 'router.query' I only see 'product-path'. Instead, each page must display the relevant 'product-name.'
I'm new to nextjs, so if someone can assist me in finding a solution, I'd appreciate it.
First of all, your object values in your product.js needs to be strings ie: "Graphics Card" instead of Graphics Card.
Normally we make new requests for data based on the dynamic URL segments. So in this case it could look something like this for example in your product.js.
import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';
import Builder from './index';
import { product } from 'data.js';
export default function Product() {
const [currentProduct, setCurrentProduct] = useState('');
const router = useRouter();
const { path } = router.query;
useEffect(() => {
const item = product.filter((item) => item.path === path);
setCurrentProduct(item[0].name);
}, []);
return <Builder>{currentProduct}</Builder>;
}