PSo PSo - 2 months ago 16
React JSX Question

React ref attribute access with name string that needed to be concatenated

In React/javascript, there is a map function like this

{this.state.caseDetails.plaintiff.map((p, i)=>{
return(
<div className={`col-lg-${inputWidth}`}>
<input type="hidden" ref={'plaintiff_id_' + i} value={p.id} />
<input type='text' ref={'plaintiff_name_' + i} className='form-control' defaultValue={p.name}/>
</div>
)
})}


I created the attributes as above plaintiff_id_0 up to the size of array by concatenate the i variable. However, the problem now is that i would like to get the value of those data using ref, So i created a for loop like this:

for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {
console.log(this.refs.("plaintiff_id_".concat(i)).value);
//Tried this.refs.("plaintiff_id_"+i).value etc.
}


And also different kind of version to concat i to the string, but it keeps telling me that this is a syntax error, is there anyway to access these ref as i want?

Answer

Try this :

for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {
      console.log(this.refs["plaintiff_id_".concat(i)].value);
  //OR
      console.log(this.refs["plaintiff_id_" + i].value);
}
Comments