The worm
The worm

Reputation: 5888

getElementById in React

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 have tried calling it in here

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

How can I get the id of an input text field and read that value and ensure it is not null?

I think the DOM is loading after I try to read the element hence why it is null

Upvotes: 42

Views: 177203

Answers (3)

Ankit Raj
Ankit Raj

Reputation: 9

import React, { useState } from "react";

function App() {
  const [name, setName] = useState("satoshi");
  const handleClick = () => {
    setName(document.getElementById("name").value);
  };
  return (
    <div>
      <input id="name" />
      <h2> {name} </h2>
      <button onClick={handleClick} />
    </div>
  );
}

export default App;

Upvotes: -3

HarshvardhanSharma
HarshvardhanSharma

Reputation: 786

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

Upvotes: 5

Shubham Khatri
Shubham Khatri

Reputation: 281656

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to 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);
  }

See this answer for more info on How to access the dom element in React

Upvotes: 32

Related Questions