Search code examples
javascriptreactjshyperlinkgatsbyreach-router

Nested route with dinamically generated link with reach router in Gatsby


I have a page generated By gatsby CreatePage with a template where I setup a Router using reach/router.

In order to show the problem, below there is a simpilfied version of the code. The router has two nested routes:

MyTemplate.js

 ...   
    <Router basepath={`/${slug}`}>
      <CategoryBar path= "/"> 
        <PostSelector path= "works" category= {category}>   
          <Post path= "test" category={category}></Post>
        </PostSelector>
      </CategoryBar>
    </Router>

In <PostSelector> component links are dinamically generated trough a .map method.

Problem: It looks like {props.children} is not passed dowm; the links are generated and rendered, but clicking them the <Post> component is not rendered.

Here the code of <PostSelector>

PostSelector.js

...
const PostSelector =( {category}, props) => { 
        return(   
            category.edges.map((post, i) => (
                <div key={i}>
                    <ul>
                    <Link to="test">{post.node.title}</Link> 
                    </ul>
                {props.children}
                </div>
                
            ))
        )
}

If i replace the dinamically generated links with hard coded link it works as expected rendering <Post> as child of <PostSelector>

Any help would be really appreciated


Solution

  • Use:

    const PostSelector =( {category, children}) => { 
            return(   
                category.edges.map((post, i) => (
                    <div key={i}>
                        <ul>
                        <Link to="test">{post.node.title}</Link> 
                        </ul>
                    {children}
                    </div>
                    
                ))
            )
    }