Skip to content
Advertisement

Duplicate components in React after click button

REACT Problem – I would like to do something like this to start the function of creating a new component after clicking on the button. Moreover I want the div element with its content to appear every time I click a button. (in my case my own component)

For example when i want to create questionnaire and add questions i need a button who let me add input for this question. You know, duplicate components.

“REACT.CreateElement”? which will be in some loop? Or maybe there are other methods do you know?

I tryed CreateElement, customElements.define() but i dont know it is correct way. Now i;m traing use. Can you help me? Thank you in advance, Below my code:

JavaScript

Advertisement

Answer

There’s quite a few things wrong here.

Firstly, be careful what you do in the body of a component. This will run every time the component renders. So firstly wrap your fetch in a useEffect:

JavaScript

This will ensure the code only runs once when the component renders.

Also if you are updating state based on a return of a promise (like you are here), you should check the component is still mounted, before setting state. You can do this yourself, or there are libraries (react-use) for this.

Next… to repeat components, this is basic and common use case. Most commonly, you would have your questions represented as an array, and loop through this to generate the components. A very contrived example:

JavaScript

This will render as many <Question /> components as what is in the array listOfQuestions. This could be an array of objects with a more complex structure, but the concept is the same. You just loop through an array and conditionally render your component. When you do this, every component needs a unique key prop, so that React knows what to do at re-rendering.

The array listOfQuestions could be a stateful value (useState()) that you update dynamically. When you do this, the rendered components will update to reflect the new values in the array.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement