I am pretty new to React and I have a requirement where I need to generate multiple div's and on button click I need to display those div's. Here is the code

    export default class Test extends React.Component {
    constructor() {
        super();
        this.state = {
            dynaDiv: {}
        };
        this.onChangeFunc = this.onChangeFunc.bind(this);
        this.buildDynamicDivs = this.buildDynamicDivs.bind(this);
    }
    onChangeFunc(inputName) {
        const testId = "test"+(Math.floor(Math.random() * Math.floor(10)));
        console.log(testId);
        console.log(this.state.dynaDiv[testId].display);
        this.setState((prevState) => {
            console.log(prevState.dynaDiv[testId]);
            return({
                ...prevState,
                dynaDiv: {
                    ...prevState.dynaDiv,
                    [testId]: {
                        ...prevState.dynaDiv[testId],
                        display: prevState.dynaDiv[testId].display == "none"?"":"none"
                    }
                }
            });
        });
    }
    buildDynamicDivs() {
        let divs = [];
        for(let i=0; i<10; i++) {
            const dydiv = "test"+i;
            this.state.dynaDiv[dydiv] = {display: "none"}
            divs.push(<div key={i} id={dydiv} style={{display: this.state.dynaDiv[dydiv].display}}>Test div{i}</div>);
        }
        return divs;
    }
    render() {
        return(
            <div>
                <button onClick={() => this.onChangeFunc("username")}>Toggle</button>
                <button onClick={() => console.log("State: ", this.state)}>State</button>
                { this.buildDynamicDivs() }
            </div>
        );
    }
}

So when user click on Toggle, a randomly generated number between 1-9 should display/hide based upon it's previous state ( if previously displayed then hide else show).

0 Answers