Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically generate pair of input fields using reactjs

Tags:

reactjs

I have tried the following code to create a react form to dynamically generate input fields to enter the series of person's name one by one. But user needs to enter the first name and last name instead of just name. So that, the form needs to generate pair of dynamic input fields. I am new to react. Can anyone please give an hint on how to accomplish this.

Note : The following code has been taken from the stackoverflow answer of @Mayank Shukla at How to implement a dynamic form with controlled components in React.JS?.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { values: [] };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  createUI(){
     return this.state.values.map((el, i) => 
         <div key={i}>
            <input type="text" value={el||''} onChange={this.handleChange.bind(this, i)} />
            <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/>
         </div>          
     )
  }

  handleChange(i, event) {
     let values = [...this.state.values];
     values[i] = event.target.value;
     this.setState({ values });
  }

  addClick(){
    this.setState(prevState => ({ values: [...prevState.values, '']}))
  }

  removeClick(i){
     let values = [...this.state.values];
     values.splice(i,1);
     this.setState({ values });
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.values.join(', '));
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          {this.createUI()}        
          <input type='button' value='add more' onClick={this.addClick.bind(this)}/>
          <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('container'));
like image 939
Prem Avatar asked Jul 21 '18 16:07

Prem


People also ask

How do you handle dynamic input fields in react JS?

How to Add the Values from inputFields State. Now, let's add the values from the inputFields state to the input fields. import { useState } from 'react'; import './App. css'; function App() { const [inputFields, setInputFields] = useState([ { name: '', age: '' } ]) return ( <div className="App"> <form> {inputFields.

How do you create a dynamic input field?

Create a button and on clicking this button we will dynamically add the input fields. Now write the click() function to handle the adding and removing functionality. Use the append() method to add the input field code to the existing HTML document.


1 Answers

Idea is, maintain an array of object in state variable. Each object will have two keys firstName and secondName (you can add more fields). Treat each object as a single unit and for all the keys render input element, and whenever user will click on add more, add one more object/entry the the array with two keys.

Working Fiddle.

Working Snippet:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    	users: [{firstName: "", lastName: ""}]
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  
  addClick(){
    this.setState(prevState => ({ 
    	users: [...prevState.users, { firstName: "", lastName: "" }]
    }))
  }
  
  createUI(){
     return this.state.users.map((el, i) => (
       <div key={i}>
    	  <input placeholder="First Name" name="firstName" value={el.firstName ||''} onChange={this.handleChange.bind(this, i)} />
          <input placeholder="Last Name" name="lastName" value={el.lastName ||''} onChange={this.handleChange.bind(this, i)} />
    	  <input type='button' value='remove' onClick={this.removeClick.bind(this, i)}/>
       </div>          
     ))
  }
  
  handleChange(i, e) {
     const { name, value } = e.target;
     let users = [...this.state.users];
     users[i] = {...users[i], [name]: value};
     this.setState({ users });
  }
  
  removeClick(i){
     let users = [...this.state.users];
     users.splice(i, 1);
     this.setState({ users });
  }
  
  handleSubmit(event) {
    alert('A name was submitted: ' + JSON.stringify(this.state.users));
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          {this.createUI()}        
          <input type='button' value='add more' onClick={this.addClick.bind(this)}/>
          <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container" />
like image 167
Mayank Shukla Avatar answered Sep 30 '22 18:09

Mayank Shukla