Is there a way in Next.js to modularize a Page Element receiving staticProps via a parsedUrlQuery?
Use case is to to open
http://localhost:3000/users/101
This is how I would like my page layout to be and Element pull in the second code snippet in [id].tsx
import CTASection from '../../components/samples/CTASection';
import { User } from "../../interfaces";
import { GetStaticProps, GetStaticPaths } from "next";
import Element from "pages/users/element";
const Element = ({ item, errors }: Props) => {
return (
<Box>
<Element />
<CTASection />
</Box>
)
}
export default Id;
export const getStaticPaths: GetStaticPaths = async () => {
// Get the paths we want to pre-render based on users
const paths = sampleUserData.map((user) => ({
params: { id: user.id.toString() },
}));
return { paths, fallback: false };
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
try {
const id = params?.id;
const item = sampleUserData.find((data) => data.id === Number(id));
return { props: { item } };
} catch (error) {
return { props: { errors: 'ERROR Loading Data' } };
}
};
However it only renders the query parameters if I insert my element.tsx
page in a non-modular fashion like this:
...
return (
<Box>
<Grid gap={2}>
<Heading as="h2" fontSize={{ base: "lg", sm: "3xl" }}>
Verifikation
</Heading>
<Box
backgroundColor={colorMode === "light" ? "gray.200" : "gray.500"}
padding={4}
borderRadius={4}
>
<Box fontSize={textSize} title={`${
item ? item.name : "User Detail"
}`}>
{item && <ListDetail item={item} />}
</Box>
</Box>
</Grid>
<CTASection />
</Box>
)
...
This is the ListDetail.tsx:
import * as React from "react";
import { User } from "../../interfaces";
type ListDetailProps = {
item: User;
};
const ListDetail = ({ item: user }: ListDetailProps) => (
<div>
<h1>User: {user.name}</h1>
<p>ID: {user.id}</p>
</div>
);
export default ListDetail;
Solution 1:
you can use gerServerSideProps
export const getServerSideProps = async ({ req, res, query, params }) => {
// your code...
// you have access to req, res, query, params, headers, cookies, and many more.
return {
props: {}
}
}