Erik
Erik

Reputation: 35

Unexpected token `switch` in switch statement React

I am getting the Unexpected token switch error from the following code:

const bodyelements = () => (
    body.map(item => (
      switch (item?.typename) {
        case 'ArticleBodyText':
          return <TextBlock dangerouslySetInnerHTML={{ __html: item?.primary?.[0].text }} />
        case 'ArticleBodyImage':
          return <ArticleBodyImage item={item} />
        default:
          break;
      )}
  )

I already tried to look the error up on stackoverflow, but the fixes I saw didn't apply to my code. Does somebody know what's wrong?

EDIT:

I changed it to this

const bodyelements = () => {
    body.map(item => (
      switch (item?.__typename) {
        case 'ArticleBodyText':
          return <TextBlock dangerouslySetInnerHTML={{ __html: item?.primary?.[0].text }} />
          break;
        case 'ArticleBodyImage':
          return <ArticleBodyImage item={item} />
          break;
        default:
          break;
      )}
      }

But I am still getting the same error

Upvotes: 0

Views: 667

Answers (2)

Osama Malik
Osama Malik

Reputation: 355

You have these issues in your code

  • Each switch case must return something if you are rendering.
  • Your switch statement should be enclosed in block quotes.
  • You should add return statement for items in map.

Try this

const bodyelements = () => {
    return ['ArticleBodyText', 'ArticleBodyImage'].map(item => {
        switch (item) {
            case 'ArticleBodyText':
                return <div>1</div>;
            case 'ArticleBodyImage':
                return <div>2</div>;
            default:
                return null;
        }
    })
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

The short function syntax have two alternatives:

  1. One that uses an expression and returns its result:

    () => ( some_expression_with_a_result )
    
  2. One that uses a block for one or more statements:

    () => { statement1; statement2 }
    

switch is a statement, so you need to use the block variant.

Upvotes: 1

Related Questions