Euridice01
Euridice01

Reputation: 2568

How can I render component that gets rendered when clicking a button to the top of the list instead of the bottom?

I have a question. I have these code snippets implemented in my class component and while it is working for the most part, I need to actual display the most recent rendered component on top of the list instead of appended to the bottom of the list. How can I do that easily?

Code snippets:

state = {
    formCount: 0
   }
   
   //click event for button
   onAddClicked = () => { 
       this.setState({formCount: this.state.formCount + 1});
   }

    //render components based on count 
   { [...Array(this.state.formCount)].map((_, i) => <Form key={i}/>)}

So I have form count in state and on clicking on a button, it will increment the count and then depending on the count, it will render the same component whenever I click on the button. However, right now it is adding the new components to the bottom instead of the top, how do I render the new component that gets rendered when clicking the button to the top of the list instead?

Upvotes: 0

Views: 83

Answers (2)

ozerodb
ozerodb

Reputation: 551

So you want to render the components in reverse order? With the most "recent" ones at the top? A simple way would be to .reverse() the array of components

Upvotes: 0

Nathanael Demacon
Nathanael Demacon

Reputation: 1217

You could use .reverse() along with .keys():

[...Array(this.state.formCount).keys()].reverse().map((i) => <Form key={i}/>)

Upvotes: 1

Related Questions