GetElementById in real life

Getting this error at the moment:

Uncaught TypeError: Cannot read property 'value' of null

I call this in my render function below:

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData}/>

I also tried calling him here.

componentWillMount: function(){
        var name = document.getElementById('name').value;
      },

How can I get the identifier of the input text field and read this value and make sure that it is not null?

I think the DOM loads after I try to read the element, so it is null

+4
source share
1 answer

You need to have your function in the life cycle componentDidMount, as it is a function that is called when the DOM loads.

Use refsto access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

. dom React

+2

Source: https://habr.com/ru/post/1658901/


All Articles