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.

4

2 回答 2

2

You can use the standard Scala zipWithIndex method:

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

Then use index to tag the appropriate input element.

于 2021-10-05T14:52:01.593 回答
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(",")))
              
            )
    ))
于 2021-10-05T14:52:14.807 回答