dn1
dn1

Reputation: 55

Div generated outside

I would like to create a div with the code below. But the div is created outside of the root div.

addDiv = (e) => {
    e.preventDefault();
    //https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
    //create a new div element
    const newDiv = document.createElement("div");
    //and give it some content
    const newContent = document.createTextNode("Hi there");
    //add the text node to the newly created div
    newDiv.appendChild(newContent);
    //add the newly created element and its content into the DOM
    const currentDiv = document.getElementById("div1");
    document.body.insertBefore(newDiv, currentDiv);   
} 





        <div className="App">
            <h1>Generate Divs</h1>
            <div onClick={this.addDiv} id="div1">
                hi
            </div>
        </div>

Upvotes: 0

Views: 329

Answers (1)

ionizer
ionizer

Reputation: 1721

Either use React states or a variable for this problem.

class App extends React.Component {
  constructor(props) {
    super(props)
    
    this.state = {
      myDivs: []
    }
  }
  
  addDiv = (e) => {
    e.preventDefault();
    let newDiv = <div>Hi there</div>
    this.setState({myDivs: [...this.state.myDivs, newDiv]})
  }
  
  render() {
    return (
      <div className="App">
        <button onClick={this.addDiv}>Add Item</button>
        <div id="div1"><h1>Hello</h1></div>
        {this.state.myDivs}
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>

If you insist on using such DOM manipulation, which is not recommended with React, I suggest something like this as using document.body.insertBefore gave me an error:

addDiv = (e) => {
  e.preventDefault();
  const newDiv = document.createElement("div");
  const newContent = document.createTextNode("Hi there");
  newDiv.appendChild(newContent);
  const currentDiv = document.getElementById("div1");
  currentDiv.appendChild(newDiv)
}

Upvotes: 2

Related Questions