sooraj viswanath
sooraj viswanath

Reputation: 13

TypeError: Cannot read property 'value' of null | reactjs |

I've 2 textboxes and 1 button as material UI components.

 </p>
        <TextField id="chatidField" />
        <br />
        <p>
          <code>Enter Your Name:</code>
          <hr />
        </p>
        <TextField id="nameField" />
        <br />
        <br />
        <Button
          variant="contained"
          color="secondary"
          onClick={addToFirebase()}
        >
          Get Your Token
        </Button>

the function that onClick calls is as follows:

  function addToFirebase() {
  var chatid = document.getElementById("chatidField").value;
  var name = document.getElementById("nameField").value;
  console.log(chatid, name);
 }

I keep getting the following error:

TypeError: Cannot read property 'value' of null

8 | var chatid = document.getElementById("chatidField").value;

9 | var name = document.getElementById("nameField").value;

full code: https://codesandbox.io/s/pqmrn4x

Upvotes: 0

Views: 1971

Answers (1)

Blue
Blue

Reputation: 22921

You have an error in your onClick handler, it should be addToFirebase not addToFirebase():

<Button
      variant="contained"
      color="secondary"
      onClick={addToFirebase}
    >

When you include (), it will run the addToFirebase function, and use the return value as the onClick handler. In addition, if the addToFirebase() function is a part of your class, you will likely need to use this.addToFirebase instead.

Upvotes: 3

Related Questions