Hi I am new to Next Js also first time posting a question on stackoverflow so please ignore the mistakes. Not much idea of Next JS works. I have a requirement where I need to use dynamic routing but the route is based on slug content.
For example i have a dynamic page defined at the root.
pages/[slugDynamic].js
but this dynamic page will have two different return statements based on the content.
ex.
/slug-page1
/slug-page2-data1
/slug-page2-data2
I will first check the text in the segment, if it contains page-1 then I will have a return statement which will fetch data from the server and return a different layout and its content. If the segment contains page-2 then I will have another return statement which will fetch data depending on data1 or data2 and so on from the server and display the content.
The restriction is that I need to use "-" in the url instead of "/".
If (url === "slug-page1") {
return <Component1 />
}
return <Component2 />
Current challenge that I am facing with SSR is it already has the UI of second Component which flicks if the url is "slug-page1"
Please let me know how can I handle this along with SEO compatibility.
This is what I have in my code. Check the router?.query to get the slug and find the component that i need to render.
const MainFunction = ({links}) {
const [routeKey, setRouteKey] = useState('');
const { slugDynamic } = router?.query;
useEffect(() => {
if (slugDynamic ) {
const slugArr = slugDynamic .split('-');
setRouteKey(slugArr[slugArr.length - 1]);
}
}, [slugDynamic]);
if(routeKey === "page1"){
return <Component1 links={links}/>
}
return <Component2 routeKey={routeKey}/>
}
export async function getServerSideProps() {
const response = await fetch('someUrl');
const list = await response.json();
const links = list.map((data) => `${data.key}`);
return { props: { links } };
}
Basic need is SEO. The content of the page should be indexed, the page is pre rendered/ssr for the search engines to crawl the data. Plus depending on the URL only that Components UI is displayed.
Whereas currently component2 UI is displayed for split of a second and then component1 UI's is displayed if the url has slug "page1" in it.