0

TLDR: When I click a button to add a new element to a list of React components, it causes the entire list to rerender and lose the states in the process. How can I prevent this?


I have a list of components containing a textarea and a few other form elements.

Excerpt:

        <FormControl  as='textarea'  onChange={e => setTopicSents(e.target.value)}></FormControl>

As you can see, I have the form input stored in a state within the component itself. I have the "Topic" component defined within a "Topics" component which renders all of the text areas.

I have a button that, upon clicking, adds a new FormControl element to the "topics" array:

        const [topics, setTopics] = useState([0])
        function addNewTopic(){
            setTopics([...topics, topics+1])
        }

            <div>
                {topics.map((i)=>  <Topic></Topic> )}
                <Row style={{height: "3em"}}>
                <div>
                    <Button onClick={addNewTopic} className="cyan-btn">Add New 
                   Topic</Button>
                </div>
            </Row>
            </div>

The problem is that when I click the button to add a new form element, it causes the entire list to rerender and clears anything that the user has typed in the form. How can I change this so that either the states are preserved upon adding a new form element, or the addition of a new one does not cause the rerendering of the other form elements?

I hope that makes sense. Any help would be appreciated!

Ailany
  • 15
  • 8
  • 1
    If you prevent the list from re-rendering, you would not see the newly added topics. The problem is you are storing the "wrong" data in the state: you do not need to store a topic index but its value. – secan Jul 11 '22 at 16:15
  • 1
    I strongly recommend you to use the callback version of `setTopics`: `setTopics((prev) => [yourNewTopic, ...prev])` – ivanatias Jul 11 '22 at 19:51

0 Answers0