React: TypeError: Cannot read property 'innerHTML' of null

I am learning React and creating a simple calculator. All HTML is created within React. I am getting a TypeError: Cannot read property ‘innerHTML’ of null. The HTML is rendered before the other functions so I am unsure why I am getting the error message.
The HTML:

function App() {
    return (
    <div className="App">

        <label>Number 1: </label>
        <input type="text" id="x"></input>

        <br></br>

        <label>Number 2: </label>
        <input type="text" id="y"></input>

        <br></br>

        <button onClick={add()}>Add</button>
        <button onClick={subtract()}>Subtract</button>

        <br></br>
        <output id="out"></output>
    </div>
  );
}

Here is where I am getting the error (at the .innerHTML):

function add() {
    var x = document.getElementById('x').innerHTML
    var y = document.getElementById('y').innerHTML
    var z = x + y
    document.getElementById("out").innerHTML = z
}

103 thoughts on “React: TypeError: Cannot read property 'innerHTML' of null”

  1. 846126 134469Hey. Really good web internet site!! Man .. Outstanding .. Fantastic .. Ill bookmark this internet web site and take the feeds alsoI am happy to locate so much valuable info here within the write-up. Thanks for sharing 189260

    Reply
  2. 427642 162421Typically I do not read post on blogs, nevertheless I would like to say that this write-up very forced me to have a look at and do so! Your writing taste has been surprised me. Thank you, quite great post. 162192

    Reply

Leave a Comment