2

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);
1
  • 1
    Object.keys ..... Commented Sep 6, 2016 at 21:01

1 Answer 1

7

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you!!! It scoops up a value of null on the first iteration of the loop for some reason. I just filter it out with an if statement. It Works...
Maybe log out the key in that forEach and make sure the key is an appropriate ref for a text input. Maybe there's some other element with a 'name_' ref? Either way, glad it's working for you :)

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.