Ad

Why Is Node.appendChild() Not Working?

- 1 answer

I have this bit of code that's later going to be used to spit out the dates in a calendar. I'm trying to do this dynamically so I can load in the dates from the current month. I'm using reactjs and I keep getting an error that appendChild is not a function. I don't see what's wrong here, according to the docs its looks correct. See documentation

let datesContainer = document.getElementById('display')

function drawCalendar() {
  for (let i = 0; i < 42; i++) {
    let dateNode = document.createElement("div")
    dateNode.textContent = toString(i)
    dateNode.setAttribute("id", "dateNode" + i)
    datesContainer.appendChild(dateNode)
  }
}
drawCalendar()

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="display">
          <div className="d-numbers" id="display">

          </div>
        </div>
      </div>
    );
  }
}
Ad

Answer

I suppose this is a Reactjs specific thing or just the timing on how the code is executed. As you can see with @MarkBaijens answer the code does work in vanilla js. @Derek Led me to the solution which was to put my function and DOM element inside a componentDidMount() method. In react the place initialize a variable with a DOM node is inside that method see documentation.

class App extends Component {
  componentDidMount() {
    let datesContainer = document.getElementById('display')

    function drawCalendar() {
      for (let i = 0; i < 42; i++) {
        let dateNode = document.createElement("div")
        dateNode.textContent = i
        dateNode.setAttribute("id", "dateNode" + i)
        datesContainer.appendChild(dateNode)
      }
    }
    drawCalendar()
  }
  render() {
    return (
      <div className="App">
        <div className="display">
          <div className="d-numbers" id="display">

          </div>
        </div>
      </div>
    );
  }
}
Ad
source: stackoverflow.com
Ad