SepSol
SepSol

Reputation: 113

How to check for object properties in a conditional statement in JavaScript?

I have a local json database and I'm trying to load different icons for different types of links that I saved there on my frontend react web application.

When I check for the condition of a property of an object, I get an error from ESLint saying Parsing error: Unexpected token. I cannot use neither switch-case nor if-else statements.

Here's my code:

        <ul className="work-links">
          {work.links.map(link => (
            <li>
              <a
                href={link.url}
                target="_blank"
                rel="noopener noreferrer"
              >
                {
                  switch (link.type) {
                    case 'website':
                      return <Globe />;
                    case 'github':
                      return <GitHub />;
                    case 'gitlab':
                      return <GitLab />;
                    case 'apk':
                      return <Android />;
                    case 'youtube':
                      return <YouTube />;
                    default:
                      break;
                  }
                }
              </a>
            </li>
          ))}
        </ul>

P.S.

Here's the link to the full code: https://github.com/sepsol/sepsol.github.io/blob/react-code/src/components/Works.js

And here's the problem in VS Code: screenshot of the problem in vs code

You can clone the repo and see the problem for yourself.

Upvotes: 0

Views: 562

Answers (1)

Liu Lei
Liu Lei

Reputation: 1297

const maps = {
 'website': <Globe />
 'github': <GitHub />,
 'gitlab': <GitLab />,
 'apk': <Android />,
 'website': <YouTube />,
}

<ul className="work-links">
  {work.links.map(link => (
    <li>
      <a 
         href={link.url}
         target="_blank"
         rel="noopener noreferrer"
      >
       {maps[link.type]}
      </a>
    </li>
   ))}
</ul>

Upvotes: 2

Related Questions