Iterate all ref values โ€‹โ€‹in a component

I'm trying to access all the ref values โ€‹โ€‹in my component and do something with them (e.g. create a payload to send to the server)

I tried to make a simple for.in loop and use the getDOMNode () value for each ref, but it does not work.

var Hello = React.createClass({

getAllRefsValues: function() {
    for(ref in this.refs) {
        console.log(ref);
        // ref.getDOMNode().value doesnt work here 
    }
},
render: function() {
    return (
     <div>
        <button onClick={this.getAllRefsValues}>Get all props values</button>
        <input type="text" ref="test1"/>
        <input type="text" ref="test2"/>
        <input type="text" ref="test3"/>
  </div>
    )
 }
});

Here is the jsfiddle I'm working with.

I have the feeling that this might not be a good idea, but I donโ€™t know how to approach this atm.

Can anybody help?

+4
source share
2 answers

This is because it this.refsis an object, you need to get the values, not the keys:

getAllRefsValues: function() {
    for (var ref in this.refs) {
        console.log(this.refs[ref]);
        console.log(this.refs[ref].getDOMNode()); 
    }
}

In my experience, it is best to use Controlled Components through refs.

+9

lodash, this.refs .

let data = _.mapValues(this.refs, function(ref) { return ref.value });
0

All Articles