Peminator
Peminator

Reputation: 862

how in reactjs checkboxes with same name keep values as array

do get to point quick

<input type="checkbox" name="name1[]" value="1" />
<input type="checkbox" name="name1[]" value="2" />

note the brackets in name [] - in classic html, posting form with this, the POST body would contain this

{name1:[1,2]}

now building a reactjs, inputs have name, ref, but can i use the brackets there too? does not seem to work... having predefined objects, trough .map() function i output the checkboxes, but how to keep their values qrouped with the shortest code?

actually, its supersimple, if i would write it as

<select ref="name1" name="name1" multiple="true" ....

how simplest way do this with checkboxes, with select i have result in this.refs["name1"], without any overhead hassle, how to do it with checkboxes pls? to avoid any crazy long coding?

Upvotes: 0

Views: 755

Answers (1)

Muhammad Mehar
Muhammad Mehar

Reputation: 1055

The way is to wrap checkbox in a parent div & then access them through its ref as follow:

<div
  ref={ref => this.inputs = ref}
>
  <input type="checkbox" name="name1" value="1" />
  <input type="checkbox" name="name2" value="2" />
  <input type="checkbox" name="name3" value="3" />
</div>
const array = this.inputs.children

const name1 = array[0]
const name2 = array[1]
const name3 = array[2]

I hope it help you.

Upvotes: 1

Related Questions