1

How do we get hold of index while looping a collection in scalajs-react component? So basically I have code like this:

<.div(
          employees.map( employee =>
            <.form(
              <.label("Name of the employee:",
                <.input(^.`type` := "text", ^.cls := "form-control",
                  ^.value := employee.name)),
              <.br,
              <.label("Addresses:",
                <.input(^.`type` := "textarea", ^.rows := 100, ^.cols := 20,^.cls := "form-control",
                  ^.value := employee.addresses.mkString(",")))
              
            )
    )
)

So if user changes a field, I need to know which employee in the employees is changed. So I need to know the corresponding index OR if there is some other better way.

Mandroid
  • 6,200
  • 12
  • 64
  • 134

2 Answers2

2

You can use the standard Scala zipWithIndex method:

employees.zipWithIndex.map{ case (employee, index) =>

Then use index to tag the appropriate input element.

Tim
  • 26,753
  • 2
  • 16
  • 29
0

The second parameter is index of the loop.

<.div(
          employees.map( (employee,index) =>
            <.form(
              <.label("Name of the employee:",
                <.input(^.`type` := "text", ^.cls := "form-control",
                  ^.value := employee.name)),
              <.br,
              <.label("Addresses:",
                <.input(^.`type` := "textarea", ^.rows := 100, ^.cols := 20,^.cls := "form-control",
                  ^.value := employee.addresses.mkString(",")))
              
            )
    ))
Sudip Thapa
  • 193
  • 1
  • 1
  • 8