nikotromus nikotromus - 1 year ago 203
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 = + i.value

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


Ian Ian
Answer Source

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 = {}; 
    .filter(key => key.substr(0,4) === 'name')
    .forEach(key => {
        values[key] = ReactDOM.findDOMNode(this.refs[key])).value || null;

Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download