1

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?

3 Answers 3

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Pick this as answer as it solved it clean and clearly and the fastest response.
1

You can use bracket notation and do: this.refs['plaintiff_id_' + i].

Comments

1

You should be able to access the DOM element using refs as follows:

for (var i = 0 ; i < this.state.caseDetails.plaintiff.length; i++) {

  var plaintiffIdRef = "plaintiff_id_" + i;
  console.log(React.findDOMNode(this.refs[plaintiffIdRed]).value)

  var plaintiffNameRef = "plaintiff_name_" + i;
  console.log(React.findDOMNode(this.refs[plaintiffNameRef]).value)

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.