Justin Blayney
Justin Blayney

Reputation: 781

Conditional statement in React return causes syntax error

I'm having syntax issues within a return. I'm trying to check if an array item exists. The issue is how I am writing the code I think.

The code causing the error is:

{ nodes.childItems ? "has child"  : "no child" } 

The error is:

Syntax error: Unexpected token, expected ","

How do I write this within my return?

  const MyNav = () => {
  const [allNavItems, setAllNavItems] = useState(null);

  useEffect(() => {
    const run = async () => {
      const items = await getNavMenu();
      
      setAllNavItems(items);
    };

    run();
  }, []);

  if (!allNavItems) return null;

  return (
    <Navbar bg="light" expand="lg">
      <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
      <Navbar.Toggle aria-controls="basic-navbar-nav" />
      <Navbar.Collapse id="basic-navbar-nav">
        <Nav className="mr-auto">
          <Nav.Link href="/">Home</Nav.Link>
            {allNavItems.menuItems && allNavItems.menuItems.nodes.map((nodes) => (
              <Nav.Link href={nodes.path}>{nodes.label}, {nodes.parentId}, {nodes.id} </Nav.Link>
              { nodes.childItems ? "has child"  : "no child "   } 
            ))}
          </Nav>
        </Navbar.Collapse>
      </Navbar>
    )
  }

Upvotes: 2

Views: 76

Answers (1)

Or Assayag
Or Assayag

Reputation: 6336

In JSX you need to include one main element, so change it to:

<>
   <Nav.Link href={nodes.path}>    {nodes.label}, {nodes.parentId}, {nodes.id} </Nav.Link>
   { nodes.childItems   ? "has child"  : "no child "   } 
</>

Upvotes: 1

Related Questions