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
}

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

  1. 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

    const App = () => {
    
        const [number1, setNumber1] = React.useState(0);
        const [number2, setNumber2] = React.useState(0);
    
        const handleChange = (e) => {
            setNumber1(e.target.value);
        };
    
        return (
            <div className="box">
                <label>Number 1: </label>
                <input
                    type="text"
                    id="x"
                    onChange={(e) => setNumber1(Number(e.target.value))}
                ></input>
                <br />
                <label>Number 2: </label>
                <input
                    type="text"
                    id="y"
                    onChange={(e) => setNumber2(Number(e.target.value))}
                ></input>
                <br />
                {number1} + {number2} = {number1 + number2}
                <br />
                {number1} - {number2} = {number1 + number2}
            </div>
        );
    };
    
    ReactDOM.render(<App />, document.getElementById("root"));
    
    Reply

Leave a Comment