Sunday 30 May 2021

React Class based - Dynamic Form -

 import React from "react";



class Form extends React.Component {

  state = {

    devices: [{name:"", password:""}],  

  }

handleChange = (e) => {

    if (["name", "password"].includes(e.target.className) ) {

      let devices = [...this.state.devices]

      devices[e.target.dataset.id][e.target.className] = e.target.value.toUpperCase()

      this.setState({ devices }, () => console.log(this.state.devices))

    } else {

      this.setState({ [e.target.name]: e.target.value.toUpperCase() })

    }

  }

addCat = (e) => {

    this.setState((prevState) => ({

    devices: [...prevState.devices, {name:"", password:""}],

    }));

  }

handleSubmit = (e) => { 

    e.preventDefault() 

    alert(JSON.stringify(this.state.devices));

}

render() {

    let { devices} = this.state

    return (

      <form onSubmit={this.handleSubmit} onChange={this.handleChange} >

        {/* <label htmlFor="name">Owner</label> 

        <input type="text" name="owner" id="owner" value={owner} />

        <label htmlFor="description">Description</label> 

        <input type="text" name="description" id="description" value={description} /> */}

        <button onClick={this.addCat}>Add new cat</button>

        {

          devices.map((val, idx)=> {

            let deviceId = `Device Name-${idx}`, passwordId = `Password-${idx}`

            return (

              <div key={idx}>

                <label htmlFor={deviceId}>{`Device #${idx + 1}`}</label>

                <input

                  type="text"

                  name={deviceId}

                  data-id={idx}

                  id={deviceId}

                  value={devices[idx].name} 

                  className="name"

                />

                <label htmlFor={passwordId}>password</label>

                <input

                  type="password"

                  name={passwordId}

                  data-id={idx}

                  id={passwordId}

                  value={devices[idx].password} 

                  className="password"

                />

              </div>

            )

          })

        }

        <input type="submit" value="Submit" /> 

      </form>

    )

  }

}

export default Form;

No comments:

Post a Comment