Conditional rendering of group field

Hi everyone,

I’ve built out a navigation model according to this tutorial:

I want to give my content editors the ability to create top level links that have sub links in a dropdown, but also to create top level links that do not. What I’m needing to do is only render my dropdown if there are fields present under the top link. Is that possible, and how could I go about it?

Jesse

Hey Jesse,

This would be done with an if statement at the project level. What technology are you building your app in? Do you have anything implemented so far?

Thanks.

So sorry, I’m building it in Gatsby! At this point all I have implemented is logic to keep the site from breaking if there are no subfields. Here’s what I’ve got:

{slice.fields.map((secondaryNav, index) => {
  if (!slice.fields) {
    return null;
  }
  <!-- markup is rendered here -->
 }

This looks over my slices and as long as the navigation item has sub fields it renders the content.

Hi there everyone! Any thoughts on this?

Thanks!

Shouldn’t that be

{
  if (!slice.fields) {
    return null;
  } else {
    return  slice.fields.map((secondaryNav, index) => {
    <!-- markup is rendered here -->
    })
  }
}

I have also followed the tutorial and to make rendering the markup easier I preprocess the result of the navigation to create a nested structure

const items = content.body.reduce((acc, el) => {
    if (acc.length === 0) {
      return [el];
    }
    const current = acc.pop();
    if (current.slice_type === el.slice_type) {
      acc.push(current);
      acc.push(el);
    } else {
      acc.push({ ...current, items: [...current.items, el] });
    }
    return acc;
  }, []);

this way I go from a flat list of navigation items which declare a nesting level to a nested list of lists of navigation items

so

[ 
  {level_1, ...item1},
  {level_2, ...item1},
  {level_2, ...item2}, 
  {level_1, ...item2},
  {level_2, ...item1},
  {level_2, ...item2},...
]

becomes

{
  {
    level_1, 
    items:[
     {level_2, ...item1},
     {level_2, ...item2}, 
    ],
    ...item1
  },
  {
    level_1, 
    items:[
      {level_2, ...item1},
      {level_2, ...item2}, 
    ],
     ...item2
  }, 
   ...
]
1 Like