JohnnyQ JohnnyQ - 1 year ago 103
React JSX Question

Save state of multiple Dynamic Components on ReactJS

Hi I have this component structure:

<ScheduleApp />
<ScheduleForm />
<TeamField />

contains a form called
and under this form I have a field where users can specify a number of teams and depends on the number the number of
is created.

My form looks like this:

enter image description here

And what I wanted is to save all the teams' names under my
component. I can save all the other states with no problem, example: the
No. of Teams
field with no problem but I'm stuck on how to save the
Team Name
fields in an array.

Here is my poor attempt on saving the array but it looks like it saves all the keystrokes I've made probably because I triggered it

enter image description here

How am I suppose to solve this problem and just save the dynamic components on the parent components' state?

Now here are my codes on jsfiddle for some reason I can't make it run on the site but will post it there for easier access.

Hope I made it clear. Any help would be much appreciated!

Answer Source

You are pushing the current content of text box into the array on every change/keystroke. Instead what you should do is text box 1 should only modify the first index in your array. And text box 2 should only modify second field in your array and so on. On each change, replace entire content with new content.

Or a cleaner approach would be to store a teams object. And send a team number field too in the on change handler against which you can store the team name.

<input className="form-control" type="text" ref="teamName"
                    onChange={this.handleChange.bind(null, 'team1')} />  // pass any index or string instead of team1
handleChange(teamIndex, teamName) {
    let { teams } = this.state;
    teams[teamIndex] = teamName;
    this.setState({teams: teams};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download