Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React find DOM node by refs set to variable?

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: ''
  });
},
like image 840
Mark Anderson Avatar asked Oct 14 '15 01:10

Mark Anderson


People also ask

How do you get the DOM element from the ref React?

We access a DOM element using the current property of a reference created with the React. createRef() function. React will update this property with an actual DOM element after render and before update events. That means that we can access the DOM element in componentDidMount and componentDidUpdate functions.

How do you get the child element in ref in React?

children should either be a ReactElement or an array of ReactElement, but not components. To get the DOM nodes of the children elements, you need to clone them and assign them a new ref. You can then access the child components via this. refs[childIdx] , and retrieve their DOM nodes via ReactDOM.

Can you use get element by ID in React?

To get an element by ID in React: Set the ref prop on the element. Use the current property to access the element in the useEffect hook.

What is FindDOMNode in React?

findDOMNode is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated in StrictMode .


1 Answers

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;
like image 96
Michelle Tilley Avatar answered Oct 03 '22 14:10

Michelle Tilley