Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over all refs values in component

I am trying to access all ref values in my component and do something with them (for example, create payload to send to a server)

I was trying to do a simple for..in loop and than use getDOMNode().value on every ref but it doesn`t 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 jsfiddle I am working with.

I have a feeling that, this might not be a good idea to do, but I have no idea how to approach this atm.

Anyone help ?

like image 337
Michał Lach Avatar asked Jun 09 '15 14:06

Michał Lach


People also ask

Can we use ref on component?

We should not use ref attribute on function components because they do not have instances. React will assign the current property with Dom element when component mount and assign null to it when component unmount. ref updates happen before componentDidMount or componentDidUpdate methods.

How do you pass a ref to a component?

We create a React ref by calling React.createRef and assign it to a ref variable. We pass our ref down to <FancyButton ref={ref}> by specifying it as a JSX attribute. React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.

What is the difference between useRef and createRef?

useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn't create a new instance of the ref for every re-render. It persists the existing ref between re-renders. createRef: The createRef is a function that creates a new ref every time.


2 Answers

This is because this.refs is 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 anyway, it is better to use Controlled Components over refs.

like image 66
gcedo Avatar answered Oct 15 '22 05:10

gcedo


Using lodash you can iterate over this.refs and create simple object.

let data = _.mapValues(this.refs, function(ref) { return ref.value });
like image 34
Deano Avatar answered Oct 15 '22 05:10

Deano