'React: same component reappearing multiple times in the app, how can I make sure that all states are captured accurately and not just the last?

I am creating an app where the user can type in a number and make as many - we will call them "mini-forms" - they want via the Add a Plus Content Line and then on the Generate Plus Content button click it should be outputted in the textarea of OutputDiv to then be copy and pasted elsewhere (later stored in a database).

However, I have run into a snag where, I cannot figure out how to have the state hold all the data present in the "mini-forms", only the data of the last updated state. I'm trying to hold an array of states, rather than just one state.

I think the fiddle is the best demo of what I am trying to achieve

The flow of data is as follows: TitleDiv -> PlusContent -> PlusContentHolder -> PlusContentForm -> App -> OutputDiv

Fiddle to demonstrate what I mean : https://jsfiddle.net/4hpbj53t/1/

One thing is, I have left the expected output logged in the console, rather than in the OutputDiv, because the console.log demonstrates that only my last state is carried through.

Any pointers in the right direction would be greatly appreciated, as I am still learning react :)



Solution 1:[1]

So I found a way, but it seems a much more Javascript way and seems to ignore many of the things which make react worth using, such an not directly interacting with the DOM: In the fiddle this will be placed in the PlusContentHolder part

const titleInfoHandler = (x) => {
    let titleArray = [];
    let allTerms = {};

    document.getElementsByName("title").forEach((title) =>{
      titleArray.push(title.value)
   })

   for(let i = 0; i < titleArray.length; i++){
     allTerms[i] = {...allTerms[i], title: titleArray[i]}
   }

    setPlusContent((prevState) => {
      return{...prevState, titleArray}})
   props.titlePointer(plusContent)
  };

I am still looking for a better way, as I have more than just a title input in this component, so any feedback, criticism etc. would be appreciated :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BoogaBooga