Search code examples
javascriptreactjsstatesemantic-ui-react

Store state of text areas belonging to different tabs


I'm trying to create something that has multiple tabs, and each tab should contain its own text area that can keep its text when going to and from each tab. My code before the render function is this

const panes = []

for(let i = 0 ; i < inputValue ; i++) {
  const formNumber = "Form: " + (i+1);

  panes.push({
    menuItem: "Form " + (i+1),
    key:{i},
    render: () => (
      <Tab.Pane >
        {i+1}
        <Form.TextArea
          onChange={this.onChange}
          key={i}
        />
      </Tab.Pane>
    )
  });
};

in the render function:

<Tab
  grid={{ paneWidth: 12, tabWidth: 2}}
  menu={{ fluid: true, vertical: true, tabular: 'right' }}
  panes={panes} 
/>

The i value in the for loop that is rendered inside the tab pane remains correct when changing tabs however the information in the text area is lost. I've tried using local state with something the code below, and then updating with an onChange function

this.state = {
  forms: [{
    formNumber: 1,
    formText: ''
  }]
}

but running into problems with inserting the information into the correct list item in the forms state. I've also tried creating a list not in the state like

this.form_text = []

and then inserting the text and assinging the values of the form text areas to that, but it seems like the wrong way to go about this


Solution

  • Add i to the onChange parameters :

    onChange={e => this.onChange(e, i)}
    

    This way you can update the correct form in the state :

    onChange = (e, i) => {
      this.setState({
        forms: this.state.forms.map(it => {
          if (it.formNumber !== i) return it; // keep other forms as is
    
          return { formNumber: i, formText: e.target.value };
        })
      });
    };