PSo PSo - 6 months ago 35
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

{, i)=>{
<div className={`col-lg-${inputWidth}`}>
<input type="hidden" ref={'plaintiff_id_' + i} value={} />
<input type='text' ref={'plaintiff_name_' + i} className='form-control' defaultValue={}/>

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++) {
//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?


Try this :

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