leonheess
leonheess

Reputation: 21349

React: Parsing error: Unexpected token, expected "..."

So I'm inside my render()-method creating some <select>. I want to select a default value but only when it's not a <select multiple>. I tried this but encountered the error in the title. How would I code this correctly?

<select key={setting.id} multiple={setting.multiple} {setting.multiple ? '' : 'value={setting.default || ""}'}><select>
                                                      ^ error occurs here

EDIT:

It is important that the select has no value-attribute at all in the case it is a <select multiple> to mitigate the The value prop supplied to <select> must be an array if multiple is true.-warning.

Upvotes: 0

Views: 912

Answers (3)

mstfyldz
mstfyldz

Reputation: 482

Something like below may solve your problem:

render(){
      let selValue = "";
      if(setting.multiple)
        val = setting.default;
      return(
        <select key={setting.id} multiple={setting.multiple} value={selValue}><select>
      )
    }

EDIT: According to your needs you can also use below code:

let select = (<select key={setting.id} multiple={setting.multiple} value={setting.default}><select>)
if(setting.multiple)
  select = (<select key={setting.id} multiple={setting.multiple}><select>)

Upvotes: 4

pawel
pawel

Reputation: 36965

In JSX, the {} do not output strings as is the case in many templating languages, you need to look at it as an assignment where the left hand is the property, e.g. multiple=, and the right hand is a JavaScript expression that returns a value to be assigned, e.g. { setting.multiple } - it gets evaluated and assigned to the multiple property.

Now to set the value depending on the setting prop just follow the same logic:

<select value={ setting.multiple ? [] : (setting.default || "") } />

EDIT: to explain why the error says expected "...". If the {} do not fall on the right side of an assignment it is expected that you want to spread multiple properties, for example
const props = { value: "foo", name: "myInput" }; <select {...props } />.

Upvotes: 2

Nayan shah
Nayan shah

Reputation: 551

How about doing it this way?

setting.multiple
? <select key={setting.id} multiple={setting.multiple}></select>
: <select key={setting.id} multiple={setting.multiple} value={setting.default || ""}</select>

Upvotes: 1

Related Questions