jamal
jamal

Reputation: 53

ReactJs: How to add/append a component on click of button

Say <componentX \> when onClick of "create box" button, the componentX should append inside of box-container. If i click create box 3 times, then three componentX should append inside box-container (It's not that simply keeping the component then hide and show when click of create box). What are all the ways to achieve this in ReactJS.

import ComponentX from './ComponentX.jsx';

class App extends React.Component{
	constructor(){
		super();
		
		this.state = {

		}
	}

	render(){
		let board = Box;

		return(
			<div>  	
				<a onClick={}>Create Box</a>
				<div className="box-container"></div>
			</div>
		);
	}
}

export default App;

Upvotes: 3

Views: 12958

Answers (2)

Philip Pavo
Philip Pavo

Reputation: 159

Try something like this:

import ComponentX from './ComponentX.jsx';

class App extends React.Component{
    constructor(){
        super();

        this.state = {
            children: [];
        }
    }

    appendChild(){
        this.setState({
            children: [
                ...children,
                <componentX \>
            ]
        });
    }

    render(){
        let board = Box;

        return(
            <div>   
                <a onClick={() => this.appendChild()}>Create Box</a>
                <div className="box-container">
                    {this.state.children.map(child => child)}
                </div>
            </div>
        );
    }
}

export default App;

Upvotes: 8

Sakhi Mansoor
Sakhi Mansoor

Reputation: 8102

You can conditionally render by using component state like this:


import ComponentX from './ComponentX.jsx';

class App extends React.Component{
    constructor(){
        super();

        this.state = {
          showComp = false;
        }
    }

    handleClick = () => {
        this.setState({
           showComp: true,
       })
    }

    render(){
        let board = Box;
        const { showComp } = this.state;

        return(
            <div>   
                <a onClick={this.handleClick}>Create Box</a>
                <div className="box-container">
                  {showComp && <ComponentX />
                </div>
            </div>
        );
    }
}

export default App;

Upvotes: 0

Related Questions