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
}

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

Leave a Comment