nikotromus nikotromus - 3 months ago 54
React JSX Question

ReactJS how to loop through dynamically named refs

I'm looking at a line of code that has dynamically named refs for an input, where 'item' is an incrementing value starting at zero.

"input type="text" ref={'name'+item} defaultValue={item} />"

How would I loop through these dynamic refs to scrape out the values? I tried this with no luck. It tells me object undefined. (the length of inputs will equate to the number of added elements)

var arr = this.state.inputs;
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
var c = this.refs.name + i.value
alert(c);
}


Though, this DOES work, but its dynamic, so I need to loop through it, not hard code it:

alert(this.refs.name0.value);
alert(this.refs.name1.value);
alert(this.refs.name2.value);

Ian Ian
Answer

I believe you need to get the DOM objects for the inputs, not just the refs (at least that has been my experience):

import ReactDOM from 'react-dom';

const values = {}; 
Object.keys(this.refs)
    .filter(key => key.substr(0,4) === 'name')
    .forEach(key => {
        values[key] = ReactDOM.findDOMNode(this.refs[key])).value || null;
    });

Good luck!