Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

dynamic forms in react

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'));
Comment

PREVIOUS NEXT
Code Example
Javascript :: Ping discord 
Javascript :: setinterval() nodejs 
Javascript :: Creating with the custom hook in react 
Javascript :: count occurence in array js 
Javascript :: append string js 
Javascript :: react native material bottom tabs 
Javascript :: bcrypt mongoose schema 
Javascript :: iterating string js 
Javascript :: Sort() functions 
Javascript :: date picker type react 
Javascript :: javascript add query string to url 
Javascript :: adb.exe: more than one device/emulator react native 
Javascript :: add column sequelize 
Javascript :: react pass object as props 
Javascript :: mongoose callback in save function 
Javascript :: javscript assert 
Javascript :: looping through json array 
Javascript :: chain id 
Javascript :: find string length javascript 
Javascript :: why bigint js 
Javascript :: isupper 
Javascript :: javascript export 
Javascript :: view child with directive not working undefined 
Javascript :: js range similar to python 
Javascript :: bootstrap carousel dynamic height jquery 
Javascript :: Material-ui add box icon 
Javascript :: js alertify.success parameters 
Javascript :: autocomplete required material ui 
Javascript :: what is package.json in node 
Javascript :: examples of Conditional Operator js 
ADD CONTENT
Topic
Content
Source link
Name
7+5 =