Zulzidan.com
Zulzidan.com

Reputation: 456

gatsby link is using the current address instead of using the root address

I want to make some pagination, but I don't know why my gatsby link is automatically adding the current address then adding the to={}.

Imagine it like this:

I want to go page2 from page1. So, I will use Link to={page1} and the link should be localhost:8000/page1 instead what I get is localhost:8000/page2/page1

Here is the actual code. In pagetemplate.js:

export default function Program({ pageContext, data }) {
      const post = data.cockpitProgram
      const { previous, next } =  pageContext
    {previous && ( 

    <Link to={previous.title.slug} rel="prev"
    
    // className={ navLinkPrev}
    >
        <div
        //  className={ navPrev}
        >      
            <h3
            style={{margin:0,
            fontSize:"1em"}}
            >
                {previous.title.value}
            </h3> 
        </div>
        <div 
        // className={ navMobilePrev}
        >
            <FontAwesomeIcon icon="chevron-circle-left"></FontAwesomeIcon>
        </div>
    </Link>
    )}

In gatsby-node.js:

const pages = res.data.allCockpitProgram.edges
        pages.forEach(( post,index ) => {
          createPage({
            path: `/${post.node.title.slug}/`,
            component: program,
            context: {
              slug: post.node.title.slug,
              previous: index === 0 ? null : pages[index - 1].node,
              next: index === (pages.length - 1) ? null : pages[index + 1].node,
            },
          });
        })

Upvotes: 2

Views: 934

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29315

If you don't set a slash (/) at the beginning, it takes the path as relative. In the example: Link to={page1} should be Link to={/page1}.

Your pageContext seems to work properly, you are fetching the previous and next page, however, you are not setting correctly the <Link>'s destination.

So, in the provided code use <Link to={`/${previous.title.slug}`} rel="prev">.

Upvotes: 3

Related Questions