Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

363
Vistas
How to create new div after clicking a button in React,Js?

I am new to React.JS. I need to make a button that creates a div with a child element every time the button is clicked. My current code does not create a new div whenever I click the button.

Also how would I create a new div with a child div inside it in React Js?

Here is my ReactJs code:

 import React from 'react';
 import ReactDOM from 'react-dom';
 import './index.css';

 class CrudDivs extends React.Component {

    renderCrudDiv(){
      console.log('clicked')
      return (
        React.createElement(
          "div",
          {className: "crud-card"},
          "NewDiv",
        )
      )
    }

    render(){

      return (

        <div className="crud-container">
          <div className = "btnContainer" >
            <button className = "makeDivsBtn"  onClick = {this.renderCrudDiv}> 
                    Create Divs
            </button>
          </div>
        </div> // container end 
        
      )
      
    }  
}

ReactDOM.render(< CrudDivs /> , document.getElementById('root'));
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Considering that every time you've to add same content.

You can create a component. For example:

Class Child extends React.Component {

render() {
  return <div>Child</div>
}

}

Now in your CrudDivs simply create a state called childrens of array time.

 import React from 'react';
 import ReactDOM from 'react-dom';

 import Child from './Child';
 import './index.css';

 class CrudDivs extends React.Component {

    constructor(props) {
        super(props);

       this.childrens = [];
     }

    renderCrudDiv(){
      const temp = [...this.childrens];
      temp.push(1); // to increase counter
      this.setState({childrens:temp});
    }

    render(){

      return (

        <div className="crud-container">
          <div className = "btnContainer" >
            <button className = "makeDivsBtn"  onClick = {this.renderCrudDiv}> 
                   
            </button>

          {this.childrens.map((_, index)=> <Child key={index} /> )}
          </div>
        </div> // container end 
        
      )
      
    }  
}

ReactDOM.render(< CrudDivs /> , document.getElementById('root'));
about 4 years ago · Juan Pablo Isaza Denunciar

0

I think that the easiest way to achieve your goal is to use state, which is a mechanism that keeps some internal data for your component and causes it to rerender. Try changing your implementation to something like this:

 import React from 'react';
 import ReactDOM from 'react-dom';
 import './index.css';

 class CrudDivs extends React.Component {
    state = {
        storedElements: [] // at the beginning there are no elements
    }
    
    renderSingleDiv() { // generate single element
        return (
          React.createElement(
          "div",
          {className: "crud-card"},
          "NewDiv",
        )
      )
    }

    renderCrudDiv(){ // update state with new element
      this.setState((prev) => {
         return { 
             storesElements: [
                 ...prev.storedElements, 
                this.renderSingleDiv()
             ]
           }
      });
    }

    render(){

      return (

        <div className="crud-container">
          <div className = "btnContainer" >
            <button className = "makeDivsBtn"  onClick = {this.renderCrudDiv}> 
                    Create Divs
            </button>
          </div>
        {storedElements} // display elements
        </div> // container end 
        
      )
      
    }  
}

ReactDOM.render(< CrudDivs /> , document.getElementById('root'));

There are for sure better ways to do this, but I was trying to keep as much from your implementation as possible. :)

about 4 years ago · Juan Pablo Isaza Denunciar

0

Looking at the code, it looks like you are coming a jQuery background where you write procedures on how to mutate the DOM on events rather than using declarative style of React.

In simpler terms, you should maintain a state (ie. count) of how many divs to display at a given time which should then be incremented on button click.

class CrudDivs extends React.Component {
    constructor(props) {
      super(props);
      this.state = {divCount: 0};
      this.renderCrudDiv = this.renderCrudDiv.bind(this);
      this.divList = this.divList.bind(this);
    }

    renderCrudDiv(){
      this.setState({divCount: this.state.divCount + 1});
    }

    divList() {
      const rowList = [];
      for (let i = 0; i < this.state.divCount; i++) {
        rowList.push(<div className="crud-card">NewDiv</div>);
      }
      return rowList;
    }

    render(){
      return (
        <div className="crud-container">
          <div className = "btnContainer" >
            <button className = "makeDivsBtn" onClick = {this.renderCrudDiv}> 
                    Create Divs
            </button>
          </div>
          {divList()}
        </div> // container end 
      )
    }  
}

This being said, as already mentioned in comments, you should use the newer functional & hook syntax rather than this deprecated one.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda