TypeError: Cannot read property 'value' of null reactJs

I am getting the following error TypeError: Cannot read property ‘value’ of null what do I need to do with value in this case please help me. Do I need to assign a value to value

function makeSearch() {
  var qty = document.getElementById('qty').value;
  if (qty > 5) {
    alert("Maximum 5 toy available.")
    return false
  }
  var cname = document.getElementById('cname').value;
  var tenure = document.getElementById('tenure').value;
  var toy = document.getElementById('toy_name').value;
  var rent = qty * tenure * toy;
  var answer = window.confirm("Total rental cost = " + rent);
  if (answer) {
    alert("Thank you for order Mr/Ms/Mrs: " + cname);
    window.location.reload();
  } else {
    alert("Order cancelled.")
    window.location.reload();
  }
  return false
}

code after
return :

  <
  tr >
  <
  td >
  Number Of toys available <
  /td> <
td >
  <
  input type = "number"
name = "avail"
id = "avail"
value = ""
readonly ref = ""
required > < /input> < /
  td > <
  /tr> <
tr >

38 thoughts on “TypeError: Cannot read property 'value' of null reactJs”

  1. You are trying to access the value of elements that are not on the page.

    Even if the elements would have been on the page you would bump into issues with code like this, cause var cname = document.getElementById('cname').value; will run before the elements are mounted to the page.

    Another issue is that in react you should not be using document.getElementById to get the value out of it.

    The correct way would be to use the react useState hook react hooks

    Reply

Leave a Comment