Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - add div's on the fly

So I am getting my hands dirty on React and I can't seem to figure out this simple problem (probably because of lack of sleep)

I want to add elements (or divs) inside the render on the fly when I click "Add Row".

How would I go on about it? Do I need to keep it in an array and within the render function, I will have to map it?

class SimpleExample extends React.Component {
    constructor(props) {
        super(props)
        this.handleAddingDivs = this.handleAddingDivs.bind(this)
    }


    handleAddingDivs() {
        const uniqueID = Date.now()
        return (
            <div>
                This is added div! uniqueID: {uniqueID}
            </div>
        )
    }

    render() {
        return (
            <div>
                <h1>These are added divs </h1>

                <button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button>
            </div>
        )
    }
}
like image 701
Alejandro Avatar asked Jun 16 '26 15:06

Alejandro


1 Answers

Let's say you want to add multiple divs, so maintain a state variable for that, count or any other data (you can use any array also and store the unique value of all the divs), then use map or any other loop to create the divs for that.

Check this working snippet:

class SimpleExample extends React.Component {
    constructor(props) {
        super(props);
        this.state = {count : 0}
        this.handleAddingDivs = this.handleAddingDivs.bind(this)
    }


    handleAddingDivs() {
        this.setState({count: this.state.count + 1})     
    }
    
    renderDivs(){
        let count = this.state.count, uiItems = [];
        while(count--)
           uiItems.push(
               <div>
                   This is added div! uniqueID: {count}
               </div> 
            )
        return uiItems;
    }

    render() {
        return (
            <div>
                <h1>These are added divs </h1>
                <button className="btn-anchor-style add-row-link" type="button" onClick={this.handleAddingDivs}>{'Add Row'}</button>
                {this.renderDivs()}
            </div>
        )
    }
}

ReactDOM.render(<SimpleExample/>, document.getElementById('app'))
<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 ='app'/>
like image 199
Mayank Shukla Avatar answered Jun 19 '26 04:06

Mayank Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!