Use ternary in .map

Hello, I’m trying to pass some routes in my React Static blog, in the ststic.confog.js file I have the following:

children: allPosts.map((post, index) => ({
  path: `/${post.slug}`,
  component: 'src/containers/Post',
  getData: () => ({
    prevPath: allPosts[index - 1].slug ? 'undefined' : '/',
    nextPath: allPosts[index + 1].slug ? 'undefined' : '/',
    post
  })
}))

It will work just fine without the ternary, like:

getData: () => ({
 prevPath: allPosts[index - 1].slug,
 nextPath: allPosts[index + 1].slug,
 post
})

But if the index is undefined, like if you’re at the start or the end of the object I want a way to return nothing, so I’ve tried the ternary like detailed and also the || assignment, but I’m not assigning anything so I’m not sure where to go with this now.

Please correct me if I did not understand you correctly, but from your description, I understand you want to check IF allPosts[index - 1].slug is undefined, use a forward dash?

I think the following should work:


children: allPosts.map((post, index) => ({
 path: `/${post.slug}`,
 component: 'src/containers/Post',
 getData: () => ({
   prevPath: typeof allPosts[index - 1].slug != "undefined"  ? allPosts[index - 1].slug : "/" ,
   nextPath:  typeof allPosts[index + 1].slug != "undefined"  ? allPosts[index + 1].slug : "/",
   post
 })
}))


1 Like

Thanks for the reply @Tomvbe :pray:

It wasn’t phrased the best so apologies, your answer is sort of what I want, the thing is, that I need to define only slug I think as I’m getting a type error on that:

Error: TypeError: Cannot read property 'slug' of undefined

Am I going about this the right way?

No, because if you try to get an out-of-bounds element: that element is undefined, so if you try to access properties on it, eg undefined.slug, that’s a type error.

prev: allPosts[index - 1] ? allPosts[index - 1].slug : '/',

Is the element at index - 1 defined? If so, get its slug property. If not /

1 Like

Thanks for this @DanCouper :ok_hand:

1 Like

Could you amend your answer @DanCouper?

all posts should be allPosts

Thanks again

1 Like