Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react'
- class Form extends Component {
- constructor(){
- super()
- this.state = {
- email: "", //-------- (5)
- password: "",
- hobby: [] //--------- (12)
- }
- } //--------- (4)
- //input Handler
- inputHandler = (e) => {
- this.setState({
- [e.target.name] : e.target.value //store the value of the input in state value and update the state value ------------ (3)
- })
- } // ---------- (2)
- //hobbyController
- hobbyController = (e) => {
- if(e.target.checked){ {/* -------- (9) */ }
- this.setState({
- hobby : [...this.state.hobby, e.target.value] //-------- (11)
- })
- }else if(e.target.checked == false){ {/* -------- (10) */ }
- let index = this.state.hobby.findIndex(ele => ele == e.target.value)
- this.state.hobby.splice(index, 1) //-------- (13)
- }
- } //----------------- (8)
- //submitHandler
- submitHandler = (e) => {
- e.preventDefault() //to avoid auto page load during submission ------------------ (16)
- let {email, password, hobby} = this.state //get the data from state -------------- (17)
- console.log(`Email: ${email}
- Password: ${password}
- Hobby: ${hobby}`);
- } // -------------- (15)
- render() {
- return (
- <form>
- {/* email */}
- <div className="form-group">
- <label htmlFor="exampleInputEmail1">Email address</label>
- <input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" name = "email" value = {this.state.email} onChange = {this.inputHandler}></input> {/* ---------- (1) */}
- </div>
- {/* password */}
- <div className="form-group">
- <label htmlFor="exampleInputPassword1">Password</label>
- <input type="password" className="form-control" id="exampleInputPassword1" placeholder="Password" name = "password" value = {this.state.password} onChange ={this.inputHandler}></input>
- </div>
- {/* hobby */}
- <label htmlFor="hobby">Hobby</label>
- {/* drawing */}
- <div className="form-check">
- <input type="checkbox" className="form-check-input" id="exampleCheck1" name = "hobby" value = "drawing" onChange = {this.hobbyController}></input> {/* ---------- (7) */}
- <label className="form-check-label" htmlFor="Drawing">Drawing</label>
- </div>
- {/* playing */}
- <div className="form-check">
- <input type="checkbox" className="form-check-input" id="exampleCheck1" name = "playing" value = "playing" onChange = {this.hobbyController}></input> {/* ---------- (6) */}
- <label className="form-check-label" htmlFor="Playing">Playing</label>
- </div>
- {/* submit */}
- <button type="submit" className="btn btn-primary" onClick = {this.submitHandler} >Submit</button> {/* ---------- (14) */}
- </form>
- )
- }
- }
- export default Form
Add Comment
Please, Sign In to add comment