Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs : Add component on click of button

Tags:

reactjs

I am trying to add a component on click of button.

Following is the fiddle for that

https://jsfiddle.net/rzv6Lrjh/92/

 render: function() {
   return (
     <div>
       <IndividualTicketInput />
       {this.state.tickets}
       <CreateTicket createTicket={this.onClick} />
     </div>
   );
  }
});

Here I am using individual component IndividualTicketInput , is it possible to do it inside single component Tickets component?

like image 200
Priya Avatar asked Jan 19 '26 10:01

Priya


1 Answers

You could store an array of tickets in state and generate a new ticket object each time you click the CreateTicket button. Store the new tickets in state and iterate over them, rendering each one to the dom. The component will rerender each time setState is called, updating the dom with your new <Ticket> component.

 state = { tickets: [] }

 render: function() {
   return (
     <div>
       <IndividualTicketInput />
       {this.state.tickets}
       <CreateTicket createTicket={this.onClick} />
       {this.renderTickets()}
     </div>
   );
  }
});

renderTickets() {
   return this.state.tickets.map(ticket => {
      return <Ticket key={ticket.id} ticket={ticket} />;
   });
}

onClick = () => {
   let newTicket = { ... };
   let tickets = this.state.tickets.unshift(newTicket);
   this.setState({tickets});
}
like image 185
andrewhl Avatar answered Jan 21 '26 08:01

andrewhl