#dynamic route
1 messages · Page 1 of 1 (latest)
Hi @placid rune. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
In Next.js, dynamic routes can be created using square brackets []. In your case, you have a dynamic route under src/app/[categorySlug]/page.tsx. To navigate to this route using the <Link> component, you can use template literals to create the link's path dynamically.
Here's an example of how you can do this:
import Link from 'next/link'
function Page({ categories }) {
return (
<ul>
{categories.map((category) => (
<li key={category.id}>
<Link href={`/app/${category.slug}`}>{category.name}</Link>
</li>
))}
</ul>
)
}
In this example, categories is an array of category objects, each with an id, name, and slug. The href prop in the <Link> component is set to /app/${category.slug}, which will resolve to the path of the dynamic route for each category.
Remember, the <Link> component is the primary way to navigate between routes in Next.js. It extends the HTML <a> tag to provide prefetching and client-side navigation between routes.
For more information, you can refer to the Next.js documentation on Linking to Dynamic Routes (https://nextjs.org/docs/app/api-reference/components/link) and Linking and Navigating (https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@placid rune kapa.ai is still learning and improving, please let us know how it did by reacting below
@finite condor where do we save the category object array?
Let me check the knowledge base for you. One moment! :books:
The category object array can be fetched from a database or an API endpoint and saved in the state of your component. You can use React's useState and useEffect hooks to fetch the data and save it in the state when the component mounts.
Here's an example of how you can do this:
import { useState, useEffect } from 'react'
import Link from 'next/link'
function Page() {
const [categories, setCategories] = useState([])
useEffect(() => {
// Fetch the categories from your API or database
// This is just a placeholder, replace it with your actual fetch call
fetch('/api/categories')
.then(response => response.json())
.then(data => setCategories(data))
}, [])
return (
<ul>
{categories.map((category) => (
<li key={category.id}>
<Link href={`/app/${category.slug}`}>{category.name}</Link>
</li>
))}
</ul>
)
}
In this example, the useEffect hook fetches the categories when the component mounts and saves them in the categories state using the setCategories function. The categories are then mapped to <Link> components.
Please note that you need to replace the fetch('/api/categories') call with your actual API call or database query.
For more information, you can refer to the Next.js documentation on Data Fetching (https://nextjs.org/docs/app/building-your-application/data-fetching) and React documentation on Hooks (https://reactjs.org/docs/hooks-intro.html).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@placid rune kapa.ai is still learning and improving, please let us know how it did by reacting below
@finite condor is there a way to do this without a server/ api route handler fetch?
Let me check the knowledge base for you. One moment! :books:
Yes, there is a way to fetch data without using a server/API route handler in Next.js. You can directly fetch data in the getStaticProps or getServerSideProps functions, which run only on the server-side and won't be included in the JS bundle for the browser. This means you can write direct database queries without them being sent to browsers.
Here's an example of how you can do this using getStaticProps:
import { loadPosts } from '../lib/load-posts'
// This function runs only on the server side
export async function getStaticProps() {
// Instead of fetching your `/api` route you can call the same
// function directly in `getStaticProps`
const posts = await loadPosts()
// Props returned will be passed to the page component
return { props: { posts } }
}
function Page({ posts }) {
// Render your page with the posts
}
In this example, loadPosts is a function that fetches data from a database or an external API. This function is called directly in getStaticProps, and the fetched data is passed to the page component as props.
For more information, you can refer to the Next.js documentation on Data Fetching (https://nextjs.org/docs/pages/building-your-application/data-fetching).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@placid rune kapa.ai is still learning and improving, please let us know how it did by reacting below
Let me check the knowledge base for you. One moment! :books:
In the context of the App Router in Next.js, if you want to use static data (like an array of categories) without fetching from a server or an API, you can directly import the data into your file and use it in your component.
Here's an example:
import Link from 'next/link'
import categories from '../data/categories' // path to your data file
function Page() {
return (
<ul>
{categories.map((category) => (
<li key={category.id}>
<Link href={`/app/${category.slug}`}>{category.name}</Link>
</li>
))}
</ul>
)
}
In this example, categories is an array of category objects, each with an id, name, and slug, that is imported from a local data file. The href prop in the <Link> component is set to /app/${category.slug}, which will resolve to the path of the dynamic route for each category.
For more information, you can refer to the Next.js documentation on Linking to Dynamic Routes (https://nextjs.org/docs/app/api-reference/components/link) and Linking and Navigating (https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@placid rune kapa.ai is still learning and improving, please let us know how it did by reacting below
@finite condor so i have to know all there routes ahead of time for this to work? what if i want just all links of href='link-number' to go to the page at src/app/[categorySlug]/page.tsx?
Let me check the knowledge base for you. One moment! :books:
If you want all links of href='link-number' to go to the page at src/app/[categorySlug]/page.tsx, you can use a catch-all route. Catch-all routes can match multiple paths and can be useful when you don't know all the routes ahead of time.
To create a catch-all route, you can add [...slug] to the file path. In your case, you can create a file at src/app/[...categorySlug]/page.tsx. This will match any route that starts with /app/.
Here's an example of how you can use the <Link> component with a catch-all route:
import Link from 'next/link'
function Page() {
return (
<ul>
{[1, 2, 3, 4, 5].map((number) => (
<li key={number}>
<Link href={`/app/link-${number}`}>Link {number}</Link>
</li>
))}
</ul>
)
}
In this example, each href prop in the <Link> components is set to /app/link-${number}, which will resolve to the path of the catch-all route for each link.
For more information, you can refer to the Next.js documentation on Dynamic Routes (https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes) and Linking and Navigating (https://nextjs.org/docs/app/building-your-application/routing/linking-and-navigating).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@placid rune kapa.ai is still learning and improving, please let us know how it did by reacting below
@finite condor
Error: Catch-all must be the last part of the URL.
at UrlNode._insert (/Users/chrisren/Development/nextjs-link-issue-reproduction/node_modules/.pnpm/next@14.0.4_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js:60:19)
at UrlNode._insert (/Users/chrisren/Development/nextjs-link-issue-reproduction/node_modules/.pnpm/next@14.0.4_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js:142:40)
at UrlNode.insert (/Users/chrisren/Development/nextjs-link-issue-reproduction/node_modules/.pnpm/next@14.0.4_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js:13:14)
at /Users/chrisren/Development/nextjs-link-issue-reproduction/node_modules/.pnpm/next@14.0.4_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js:165:46
at Array.forEach (<anonymous>)
at getSortedRoutes (/Users/chrisren/Development/nextjs-link-issue-reproduction/node_modules/.pnpm/next@14.0.4_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/shared/lib/router/utils/sorted-routes.js:165:21)
at Watchpack.<anonymous> (/Users/chrisren/Development/nextjs-link-issue-reproduction/node_modules/.pnpm/next@14.0.4_react-dom@18.2.0_react@18.2.0/node_modules/next/dist/server/lib/router-utils/setup-dev-bundler.js:1601:65)
Let me check the knowledge base for you. One moment! :books: