Skip to content

Instantly share code, notes, and snippets.

@santosh
Created March 11, 2020 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santosh/1d650d9b4d415de2780bb53207c7f197 to your computer and use it in GitHub Desktop.
Save santosh/1d650d9b4d415de2780bb53207c7f197 to your computer and use it in GitHub Desktop.
React Forms.
class App extends React.Component {
constructor() {
super()
this.state = {
firstName: "",
lastName: "",
age: null,
location: "",
gender: "",
dietaryRestrictions: {
isVegan: false,
isKosher: false,
isLactoseFree: false,
},
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
const { name, value, checked, type } = event.target
type === "checkbox" ?
this.setState(prevState => {
return {
dietaryRestrictions: {
...prevState.dietaryRestrictions,
[name]: checked
}
}
})
:
this.setState({ [name]: value })
}
render() {
return (
<main>
<form>
<input
name="firstName"
onChange={this.handleChange}
placeholder="First Name"
/>
<br />
<input
name="lastName"
onChange={this.handleChange}
placeholder="Last Name"
/>
<br />
<input
name="age"
onChange={this.handleChange}
placeholder="Age"
/>
<br />
<label>
<input
name="gender"
type="radio"
value="male"
onChange={this.handleChange}
/> Male
</label>
<label>
<input
name="gender"
type="radio"
value="female"
onChange={this.handleChange}
/> Female
</label>
<br />
<label>Location: </label>
<select
name="location"
onChange={this.handleChange}
>
<option>Pune</option>
<option>Bengaluru</option>
<option>Delhi</option>
<option>Patna</option>
</select>
<br />
<label>
<input
type="checkbox"
name="isVegan"
onChange={this.handleChange}
/> Vegan
</label>
<br />
<label>
<input
type="checkbox"
name="isKosher"
onChange={this.handleChange}
/> Kosher
</label>
<br />
<label>
<input
type="checkbox"
name="isLactoseFree"
onChange={this.handleChange}
/> Lactose Free
</label>
<br />
<button>Submit</button>
</form>
<hr />
<h2>Entered information:</h2>
<p>Your name: {this.state.firstName} {this.state.lastName}</p>
<p>Your age: {this.state.age}</p>
<p>Your gender: {this.state.gender}</p>
<p>Your destination: {this.state.location}</p>
<p>Your dietary restrictions:</p>
<ul>
<li>Vegan? {this.state.dietaryRestrictions.isVegan ? "Yes" : "No"}</li>
<li>Kosher? {this.state.dietaryRestrictions.isKosher ? "Yes" : "No"}</li>
<li>Lactose Free? {this.state.dietaryRestrictions.isLactoseFree ? "Yes" : "No"}</li>
</ul>
</main >
)
}
}
ReactDOM.render(<App />, document.getElementById("root"))
// Use this.state.?? to set initial "value" of inputs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment