0

This is the portion of code through which I was playing

function Give({need}){
  let type1={need===true?'chemist':'others'}
  let type2={need}===true?'chemist':'others'
}

I read that The curly braces are a special syntax to let the JSX parser know that it needs to interpret the contents in between them as JavaScript instead of a string. So I was expecting both of these to work but only the second one is working even though inside brace in type1 I have javascript expression. I got this error, what does it even mean??

/App.js: Unexpected token, expected "," (4:17)

  2 | ....
  3 | function Give({need}){
> 4 |   let type1={need===true?'chemist':'others'}
    |                 ^
  5 |   let type2={need}===true?'chemist':'others'
  6 | }

Can someone please help with the reason for this behavior?

cheems
  • 164
  • 7

2 Answers2

1

This is more of a Javascript question rather than a react question tho.

Nonetheless on the Give() function, you are receiving a parameter that you are destructuring by typing {need} so that object must have a property named "need", so now that you are destructuring, need should be used directly like another answer here:

opt 1: let type = need===true?'chemist':'others'

opt 2: let type = need ? 'chemist':'others' (this one works like this because you know that need is a boolean)

Here's a useful link to know a little bit more about this:

destructuring ternary operator

0

{need} is destrucing and let type={need===true?'chemist':'others'} is an invalid condition it could be someting like let type = need===true?'chemist':'others' or moreover let type = need ? 'chemist':'others'

please checkout how javascript works. none of these are react things.

Shyam
  • 21
  • 3