0

I am using slug page directory with next.js.

My directory is

Pages
-Main
--[cat]
---[content].js

When i use next/link from another page to go content page it works and loads fine. But when i use some other link like main/cat/content inside from [content].js page, next.js changes url but not load page. If i reload the page new page shows correctly.

<li key={x.categoryid}>
    <Link href={`/main/${x.caturl}/${x.contenturl}`} key={x.title}>
    <a>
      <span>{x.title}</span>
    </a>
    </Link>
</li>

this does not work as i said.

 <li key={x.categoryid}>
    <a href={`/main/${x.caturl}/${x.contenturl}`}>
      <span>{x.title}</span>
    </a>
  </li>

this one works but will cause problems at build because of using a.

How can i use next/link correctly? Current scenario is changing url and scroll up to page.

Edit: [content].js page look like

export async function getServerSideProps({params}) {
    const { cat,content}= params;
    const https = require('https');
    const main = await fetch('https://localhost:7715/api/content/'+params.cat+'/'+params.content+'', {method: "GET" });
    if (main.status != 200) {
        
        return {
            redirect: {
                destination: '/404',
                permanent: false,
              },
            props: {
                notFound: true
            }
        }
    }
    else{
        const mycontent = await main.json();
        return {
            props: {
                data: JSON.stringify(mycontent) ||null,
            }
        }
    }
}

class Content extends React.Component {
    constructor(props){
    super(props);
    const pageData = JSON.parse(props.data);
    this.state ={
            pageData : pageData,
    }}
    render(){
          return(
          <>
           page title is {this.state.pageData.title}
          </>
          )
    }

}
  • This may not be a routing problem, but rather an issue with `[content].js` not re-rendering correctly when the route changes. Can you provide the full code for the `[content].js` page? – juliomalves Sep 02 '22 at 18:00
  • @juliomalves i edit my question. that is how my [content].js page looks like more or less – comeonalready Sep 05 '22 at 13:34
  • 1
    Is there a reason you're using state? Could you not just render `JSON.parse(props.data)` directly? – juliomalves Sep 05 '22 at 14:12
  • @juliomalves i actually try convert page to a function and get rid of constructor. now it works like expected. i didn't expect that actually. thanks for your help! – comeonalready Sep 06 '22 at 06:23

1 Answers1

0

for anyone wondering how i resolve the issue, i use function, get rid of react class and constructor. now it loads properly. thanks to @juliomalves 's answer.

 export default function Content(props) {
      
            const pageData = JSON.parse(props.data);
    
            return(
                <>
                  {pageData.title} is the title
                </>
            )
    }