Charles Belcher
Charles Belcher

Reputation: 121

Trying (and failing) to write if/else expression in JSX

I am trying to write an if/else or conditional that returns a select box with different options in different conditions.

Precisely, when a taskCard is rendered, if the task's userId = 0, I want the select box to be prepopulated with "Assign To:" as the option AND I want all of the company's employees to appear as options beneath. If the task's userId matches the employee's Id, I want the employee's name to prepopulate the box and the remainder of the company's employees to show as options as well.

For some reason, I can't wrap my head around how to do this. I understand that React doesn't allow if/else statements, but even writing this as a ternary statement has caused me problems. I currently have working:

{this.props.employees.map(employee => {
  if (employee.id === this.props.task.userId) {
  return <option key={employee.id} id={employee.id} defaultValue={employee.id} selected>
  {employee.name} {employee.surname}
  </option>

  }  else {

  return <option key={employee.id} id={employee.id} value={employee.id} >
  {employee.name} {employee.surname}
  </option>
      }
    })}
   </select>

but this does not offer me the "Assign To:" option that I am looking for.

Upvotes: 1

Views: 41

Answers (2)

wiesson
wiesson

Reputation: 6832

The first part could be simplified to reduce code duplication. The only difference of your condition is the selected prop, so if employee.id === this.props.task.userId equals true it's selected, otherwise not.

<select defaultValue={...}>
{this.props.employees.map(employee => (
  <option
    key={employee.id}
    id={employee.id}
    selected={employee.id === this.props.task.userId}
  >
    {employee.name} {employee.surname}
  </option>
));
</select>

The "assign to" option can simply be added before or after the map iteration.

<select defaultValue={this.props.task.userId}>
  {this.props.task.userId === 0 
    ? <option value="0">Assign To:</option> 
    : null
  }

  {this.props.employees.map(employee => (
    <option
      key={employee.id}
      id={employee.id}
      selected={employee.id === this.props.task.userId}
    >
      {employee.name} {employee.surname}
    </option>
  ))};
</select>

See the docs about conditional rendering

Upvotes: 1

Charles Belcher
Charles Belcher

Reputation: 121

With the suggestion below, and some additional guidance, I arrived at the following solution:

{this.props.task.userId === 0
 ? <option value="0">Assign To:</option>
 : ""}

 {this.props.employees.map(employee => (
 <option
   key={employee.id}
   id={employee.id}
   defaultValue={employee.id}
   selected={employee.id === this.props.task.userId}
                                    >
   {employee.name} {employee.surname}
   </option>
   ))
   };
   </select>

And this does exactly what I was hoping to get the application to do. Thank you very much for the thoughts and extra eyes!

Upvotes: 0

Related Questions