1

Let me start with an example so you guys can know what is the issue and what I want to achieve.

In my project I'll have multiple user form on the same page and number of forms will be dynamic (depends on user number if there are 3 users then 3 forms, if 10 users then 10 forms etc).

Let's assume all forms will have 3 fields (keep it simple here) like firstName , middleName , lastName.

Now let assume we have 3 users so 3 inputs will appear on the page.

<form>
  <input type="text" name="firstName" value="" />
  <input type="text" name="middleName" value="" />
  <input type="text" name="lastName" value="" />
</form>

We have 3 users this time so above form will appear 3 times. Here actually what I have taken only one form for all 3 users. What I have done is shown below.

<form>
  for (let i = 1; i <= 3; i++) {
   <input type="text" name="firstName" value="" />
   <input type="text" name="middleName" value="" />
   <input type="text" name="lastName" value="" />
  }
  <input type="submit" value="Submit">Apply</button>
</form>

When user submits the form I want an array of value for each form field.

What and How result I want is below.

['tome hanks' , 'shahrukh khan', 'john'] // firstname of all 3 users

['tome hanks' , 'shahrukh khan', 'john'] // middlename of all 3 users

['tome hanks' , 'shahrukh khan', 'john'] // lastname of all 3 users

I have tried this tutorial but not exactly what I need.

Maybe I can achieve this using React state but don't know how?

If Redux is helpful than it's fine for me.

2 Answers 2

3

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [
        { firstName: 'John1', middleName: 'Daniel1', lastName: 'Paul1' },
        { firstName: 'John2', middleName: 'Daniel2', lastName: 'Paul2' },
        { firstName: 'John3', middleName: 'Daniel3', lastName: 'Paul3' },
        { firstName: 'John4', middleName: 'Daniel4', lastName: 'Paul4' },
      ],
    };
  }

  _onChangeUser = (index, field, event) => {
    const newValue = event.target.value;
    this.setState(state => {
      const users = [
        ...state.users.slice(0, index),
        {
          ...state.users[index],
          [field]: newValue,
        },
        ...state.users.slice(index + 1),
      ];
      return {
        users,
      };
    });
  };

  _onSubmit = event => {
    event.preventDefault();
    // Do something with this.state.users.
    console.log(this.state.users);
  };

  render() {
    return (
      <div className="App">
        <form onSubmit={this._onSubmit}>
          {this.state.users.map((user, index) => (
            <div key={index}>
              <input
                value={user.firstName}
                onChange={this._onChangeUser.bind(this, index, 'firstName')}
              />
              <input
                value={user.middleName}
                onChange={this._onChangeUser.bind(this, index, 'middleName')}
              />
              <input
                value={user.lastName}
                onChange={this._onChangeUser.bind(this, index, 'lastName')}
              />
            </div>
          ))}
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"><div>

Sign up to request clarification or add additional context in comments.

4 Comments

let me try your answer.
for users state you have taken 4 users static but I want dynamic user state how can I do that ? this.state = {users : ['firstname': " " , "middlename": " ", "lastname" : " "]} will work ?
sometimes I have 2 users , 5 users , 10 users, 20 users for that how to set users state ?
Yes 4 is just an example, there's no hardcoding so just change the initial array values and it'll work.
0

Ok. Declare your state variable as an array. Below should fulfill your requirement.

 constructor(props){
    super(props)
    this.state={
         firstNameArray:[],
         middleNameArray:[],
         lastNameArray:[],
         fName:” “,
         mName:””,
         lName:””
    }

   this.changeFirstName = this.changeFirstName.bind(this);
   this.changeMiddleName=             this.changeMiddleName.bind(this);
   this.changeLastName=this.changeLastName.bind(this);
   }

   changeFirstName(event){
   this.setState({
          firstNameArray:event.target.value,
          fName: event.target.value
   })

   changeMiddleName(event){
   this.setState({
   middleNameArray: event.target.value,
   mName: event.target.value
   })
  }

  changeLastName(event){
  this.setState({
   lastNameArray: event.target.value,
   lName: event.target.value
   })

Call each function on your input field like below

    <input type=‘text’ name=‘fName’ value=    {this.state.fName} onChange={this.changeFirstName} />

Do it in the same way for other two input fields as well. Hope this answers your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.