Search code examples
jsxgatsby

Can you use ID on elements in Gatsby.js (JSX)?


I'm building out a navbar component using Gatsby.js. I've added an input and corresponding label which is throwing the error shown in the image below:

"Unterminated JSX contents" with error pointing towards closing tag of

import React from 'react'
import { Link } from 'gatsby'
import * as styles from "../styles/navbar.module.scss" 

   const Navbar = () => {
      return (
    
        <input type="checkbox" id="menu">
        <label for="menu" onclick></label>
    
        <nav role="off-canvas">
          <ul className={styles.navbar}>
            <li><Link to="/page-1">Page 1</Link></li>
            <li><Link to="/page-2">Page 2</Link></li>
            <li><Link to="/page-3">Page 3</Link></li>
          </ul>
        </nav>
      )
    }

export default Navbar

I'm thinking the error has to do with the ID usage within the label and input tags.


Solution

  • Your problem in the snippet above is that your Navbar returning JSX structure is not being wrapped by anything (even you have an unclosed input tag). It's perfectly valid to use ids on your elements, it has nothing to do with using it.

    Just use:

       const Navbar = () => {
          return (
            <>
            <input type="checkbox" id="menu" />
            <label for="menu" onclick></label>
        
            <nav role="off-canvas">
              <ul className={styles.navbar}>
                <li><Link to="/page-1">Page 1</Link></li>
                <li><Link to="/page-2">Page 2</Link></li>
                <li><Link to="/page-3">Page 3</Link></li>
              </ul>
            </nav>
           </>
          )
        }
    

    <> is a React fragment shorthand for <React.Fragment> and they allow you to wrap children without modifying DOM structure. More details: https://reactjs.org/docs/fragments.html