Search code examples
javascripthtmlreactjsdomappendchild

Cannot read property 'appendChild' of null react


I am trying to dynamically add new input fields using this js guide. Everything works with pure js but when I try to adapt it to react I get this error: TypeError: Cannot read property 'appendChild' of null

import React, { Component } from "react";

class addTeams extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
    };
  }


  addInput(divName) {
    var counter = 1;
    var limit = 5;
    if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
  }

  render() {
    return (
      <div class="container">
        <div class="row">
          <div class="col-md-6 col-md-offset-3">
            <div class="jumbotron text-center">
              <form method="POST">
                <div id="dynamicInput">
                  Entry 1<br></br><input type="text" name="myInputs[]"></input>
                </div>
                <input type="button" value="Add another text input" onClick={this.addInput('dynamicInput')}></input>
              </form>
              <button type="submit" onClick={this.addTournament} class="btn btn-primary">Submit</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default addTeams;

Solution

  • Did you check that addInput work?

    In constructor, try to type this.addInput = this.addInput.bind(this);

    And you should change the counter variable in addInput scope to state object.