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
}
You need to check tutorials on react, this is very basic start to learn code and not full proof but it will explain you how react works.
For react, you don’t need to get DOM values, it is react which manages the dom.
Codepen : https://codepen.io/ktdev/pen/rNWwNVJ