maifs
maifs

Reputation: 1171

How to open to the dynamic page path in nextjs?

I am trying to use the dynamic path by using nextjs app.

I am developing a CMS system and my pages run through nextjs.

In my react admin application, user can add and design multiple pages.
There is an end-user nextjs application which allow the users to get these dynamic pages.

For example: Application Admin added aboutus page and now user can access this page by typing the following in the browser.

http://localhost:3000/aboutus

This should work but it doesn't. The First thing is nextjs give an error when we try to use useRouter hook and get a pathname (it shows an error) and try to find the aboutus.js page component which doesn't exist physically.

Second thing is that we need a react component something like App.js component so that we can identify the dynamic page and call our logic to show the page but in nextjs there is nothing like App.js component nor index.js component. Nextjs has MyApp.js component which is a start point to trigger each page component with its properties but I can't write the logic here.

What I want is that to access the dynamic pages using dynamic route path. following should work

http://localhost:3000/aboutus
http://localhost:3000/contact

Please see my code below

========================================package.json==================================
{
    "name": "test",
    "version": "0.1.0",
    "private": true,
    "scripts": {
        "dev": "next dev",
        "build": "next build",
        "start": "next start",
        "lint": "next lint"
    },
    "dependencies": {
        "bootstrap": "^5.0.2",
        "next": "11.0.1",
        "node-sass": "^4.14.1",
        "react": "17.0.2",
        "react-bootstrap": "^1.6.1",
        "react-dom": "17.0.2",      
        "swr": "^1.0.0"
    },
    "devDependencies": {
        "eslint": "7.29.0",
        "eslint-config-next": "11.0.1"
    },
}

=================================================MyApp======================================

import "../styles/styles.css";
function MyApp({ Component, pageProps }) {
    return (
        <SharedProvider>
            <Component {...pageProps} />
        </SharedProvider>
    );
}
export default MyApp;




 ==========================================================index.js=======================

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import Head from "next/head";
import Layout from "../components/layout/layout";
function Home({ resData }) {
    const router = useRouter();
    const { permalink } = router.query;
    const [pageId, setPageId] = useState(0);

    useEffect(() => {
        onLoad();
    }, []);
    function onLoad() {

        let range = document.createRange();
        const wrapper = document.querySelector(".ic-container");
        wrapper.innerHTML = "";
        wrapper.appendChild(range.createContextualFragment(resData.PageContent));
    }

    return (
        <>
            <Head>
                <title>{resData.Title}</title>
                <meta property="og:description" name="description" content={resData.MetaDescription} key="description" />
                <meta property="og:keywords" name="keywords" content={resData.Keywords} key="keywords" />
                <meta property="og:title" name="title" content={resData.MetaTitle} key="title" />
                <meta property="og:author" name="author" content="test" key="author" />
                <link rel="stylesheet" href="/assets/minimalist-blocks/content.css" />
                <link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" rel="stylesheet" type="text/css" />
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
                <script
                    src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
                    integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ"
                    crossorigin="anonymous"
                ></script>

            </Head>
            <Layout>
                <div className="ic-container">
                    <div></div>
                </div>
            </Layout>
        </>
    );
}

export async function getServerSideProps(context) {
    const { perm } = context.query;
    let resData = "";
    try {    
        const fetchResponse = await fetch("http://localhost:3001/asa/page/pageByPer/" + perm);
        const data = await fetchResponse.json();
        const responseData = data && data.page && data.page.length > 0 ? data.page[0] : "";
        initialData = responseData;
        if (data) {
            if (data.isExist > 0) {
                lpageId = responseData.Id;
            }
        }
    } catch (e) {
        console.log(e);
    } finally {
    }
    return {
        props: {
        resData,
        },
    };
}

export default Home;

What is the best fix for it ? thank you for the help

enter image description here

Upvotes: 0

Views: 553

Answers (1)

tekf
tekf

Reputation: 104

Juliomalves is right.

Create a component like this [page].js under pages directory.

Following 'll work. Please try following

const Page = ({ resData }) => {
const router = useRouter();   
const { page } = router.query;
    const [pageId, setPageId] = useState(0);

    useEffect(() => {
        onLoad();
    }, []);
    function onLoad() {

        let range = document.createRange();
        const wrapper = document.querySelector(".ic-container");
        wrapper.innerHTML = "";
        wrapper.appendChild(range.createContextualFragment(resData.PageContent));
    }

    return (
        <>
            <Head>
                <title>{resData.Title}</title>
                <meta property="og:description" name="description" content={resData.MetaDescription} key="description" />
                <meta property="og:keywords" name="keywords" content={resData.Keywords} key="keywords" />
                <meta property="og:title" name="title" content={resData.MetaTitle} key="title" />
                <meta property="og:author" name="author" content="test" key="author" />
                <link rel="stylesheet" href="/assets/minimalist-blocks/content.css" />
                <link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" rel="stylesheet" type="text/css" />
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
                <script
                    src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
                    integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ"
                    crossorigin="anonymous"
                ></script>

            </Head>
            <Layout>
                <div className="ic-container">
                    <div></div>
                </div>
            </Layout>
        </>
    );
}

export async function getServerSideProps(context) {
    const { page } = context.query;
    let resData = "";
    try {    
        const fetchResponse = await fetch("http://localhost:3001/asa/page/pageByPer/" + page );
        const data = await fetchResponse.json();
        const responseData = data && data.page && data.page.length > 0 ? data.page[0] : "";
        initialData = responseData;
        if (data) {
            if (data.isExist > 0) {
                lpageId = responseData.Id;
            }
        }
    } catch (e) {
        console.log(e);
    } finally {
    }
    return {
        props: {
        resData,
        },
    };
}

Upvotes: 1

Related Questions