Manav Saxena
Manav Saxena

Reputation: 473

React Dynamically add n divs to the page on button click

I am new to react, I want my webpage to initially have 20 rectangle and then when I click a button the virtual DOM should reload and add 20 more boxes.

I have thought about setting state to 20 initially and then incrementing it by 20 everytime the button is clicked but I am not sure what to do next, do I need to run a loop till the value of state and add the divs or is there some other better way of dynamically adding elements.

Here is the code so far:-

index.js

import React from 'react';
import { render } from "react-dom";

import { Sample } from "./components/Sample";

class App extends React.Component {

    render() {

        return (
            <div className="wrapper">



            </div>
        );

    }
}

render(<App />, window.document.getElementById("app"));

Sample Component Sample.js

import React from "react";
import { index } from "./../index";
export class Sample extends React.Component {

    constructor() {
        super();
        this.state = {
            count: 20
        }
    }
    incrementCount() {
        this.setState({
            count: this.state.count += 20
        });
    }
    render() {
        return (
            <div>
                // Dynamically add divs to index.js
                <button onClick="incrementCount">Generate new boxes</button>
            </div>
        );
    }
}

Upvotes: 0

Views: 5829

Answers (1)

Chen
Chen

Reputation: 147

In your incrementCount() method, you can't modify state directly, you can change it to:

this.setState({
    count: this.state.count + 20
});

Then, you can dynamically rendering different number of divs by creating a for loop:

getrDivList () {
    var divList = null;
    for (var i = 0; i < this.state.count; i++) {
        divList.push(<div />);
    }
    return divList;
}

render() {
    return (
        <div>
            // Dynamically add divs to index.js
            { this.getrDivList() }
            <button onClick="incrementCount">Generate new boxes</button>
        </div>
    );
}

Upvotes: 2

Related Questions