Home > Mobile >  scalajs-react: How to know index of the entry while looping a Seq?
scalajs-react: How to know index of the entry while looping a Seq?

Time:10-06

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.

CodePudding user response:

You can use the standard Scala zipWithIndex method:

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

Then use index to tag the appropriate input element.

CodePudding user response:

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(",")))
              
            )
    ))
  • Related