0

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

1
  • Pass function reference rather than call in onCick={addToFirebase} Commented Nov 23, 2018 at 5:18

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@HemadriDasari They're null, because at the time that addToFirebase() is run, the actual DOM hasn't been rendered yet, so none of the elements with those ID's exist. After applying the onClick function correctly, when the button gets clicked, those elements should indeed exist in the DOM, and the error should go away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.