Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I write Javascript function in React JSX?

I got this error called "TypeError: Cannot read properties of undefined (reading ‘split’)"
I am aware of where the error came from, but I don’t know how to put the right code in it.
I am using Next.js and TailwindCSS 🙂

The code below is what I wrote:

 {productCategories.map(m => (
          <li className="group relative hover:cursor-pointer" key={m.databaseId} onClick={() => onClickParentMenu(m.databaseId)}>
            <Link passHref href={`/${m.url.split('/').splice(2, 2).join('/')}`}>
              <a className={`${router.asPath === '/' ? 'hover:text-white' : 'text-black hover:opacity-50'} ${clickedParentId === m.databaseId && 'font-bold'}`}>{m.name}</a>
            </Link>
            <ul className="absolute hidden text-gray-500 pt-4 group-hover:block">
              {m.children.nodes.map(c => (
                <li key={c.databaseId} className="w-auto whitespace-nowrap shadow-md bg-white hover:bg-gray-100 hover:text-black py-2 px-4 block" onClick={() => onClickChildMenu(c.databaseId)}>
                  <Link passHref href={`/product-category/${m.slug}/${c.slug}`}>
                    <a className={`${clickedChildId === c.databaseId && 'font-bold'}`}>{c.name}</a>
                  </Link>
                </li>
              ))}
            </ul>
          </li>
        ))}

The code that makes the error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 <Link passHref href={`/${m.url.split('/').splice(2, 2).join('/')}`}>

>Solution :

Inside the same file of your component, you can define:

function extractURL(category) {
  if (!category.url) {
    // handle the problem somehow and return an appropriate value
  }
  return `/${category.url.split('/').splice(2, 2).join('/')}`;
}

And call it like:

<Link passHref href={extractURL(m)}>...</Link>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading