How to create React Form
Example 1:
import React, { Component } from 'react'
export default class Form1 extends Component {
constructor(props){
super(props);
this.state={value:''};
this.handlesubmit=this.handlesubmit.bind(this);
this.handlechange=this.handlechange.bind(this);
}
handlechange(event){
this.setState({value:event.target.value})
}
handlesubmit(event){
alert('Hello value is '+this.state.value);
}
render() {
return (
<div>
<form onSubmit={this.handlesubmit}>
<h1>Controller Form Example</h1>
<input type="text" name="txt1" onChange={this.handlechange} />
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
Handle Multiple Inputs
import React, { Component } from 'react'
export default class Form1 extends Component {
constructor(props){
super(props);
this.state={fname:'',lname:'',email:'',address:''};
this.handlesubmit=this.handlesubmit.bind(this);
this.handlechange=this.handlechange.bind(this);
}
handlechange(event){
const name = event.target.name;
const value = event.target.value;
this.setState({[name]:value})
}
handlesubmit(event){
alert('Fname is '+this.state.fname+' ,Last Name is '+this.state.lname+', Email Address is '+this.state.email+', Address is='+this.state.address );
}
render() {
return (
<div>
<form onSubmit={this.handlesubmit}>
<h1>Controller Form Example</h1>
<label> Enter First Name <input type="text" name="fname" onChange={this.handlechange} /></label> <br />
<label> Enter Last Name <input type="text" name="lname" onChange={this.handlechange} /></label> <br />
<label> Enter Address <input type="text" name="address" onChange={this.handlechange} /></label> <br />
<label> Enter Email <input type="text" name="email" onChange={this.handlechange} /></label> <br />
<input type="submit" value="Submit" />
</form>
</div>
)
}
}