React find DOM node by refs set to variable?

21,614

Solution 1

var Value = React.findDOMNode(this.refs.refID).value;

finds the DOM node for the component with the ref "refID". If you want to find the DOM node for the component with the ref refID (the variable), you need

var Value = ReactDOM.findDOMNode(this.refs[refID]).value;

Solution 2

I had to do

import ReactDOM from 'react-dom';
ReactDOM.findDOMNode(this.refs.hi);

in React 15.2.1 (https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode)

Share:
21,614
Mark Anderson
Author by

Mark Anderson

Updated on August 17, 2020

Comments

  • Mark Anderson
    Mark Anderson almost 4 years

    I am dynamically creating multiple text inputs (with dynamically created refs) along side the text that I want updated with the input.

    I am trying to get the value of the input by setting the ref to a variable and finding the DOM node with React.findDOMNode(this.refs.Variable).value

    I am getting a "Cannot read property 'value' of null" error.

    How can I achieve this?

    This is what the function looks like:

    resetUnit: function(e){
      var refID = e.target.id;
      var ID = refID.split("-")[0];
      var Value = React.findDOMNode(this.refs.refID).value;
      NodesCollection.update({_id: ID},{$set: { materialUnit : Value}});
      this.setState({
        edit: ''
      });
    },