0

Is there a way to generate the state values from a form automatically. Say I have a form with 100000 input all have random names so not like name_1 name_2 or so. Names are not automatically generated or anything.(Which i do not have but just curious).

Can I generate the state values automatically for each input field. We can have one function to handle input and use e.target.name and e.target.value to set the state. But can we initialize the state with these names to empty values. You create the state in constructor and so constructors would not have an idea of the fields yet. Or do we leave the state empty initially and we add the new field to state when onChange happens. We check if the name is in the state if so update if not deep copy the old state and add the new name/value and set it as the new state ?

Thanks.

I am just after a better way to do this.

Evren Bingøl
  • 1,306
  • 1
  • 20
  • 32

2 Answers2

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

Article : https://medium.com/@bretdoucette/understanding-this-setstate-name-value-a5ef7b4ea2b4

Reactjs setState() with a dynamic key name?

Mahdi Sheibak
  • 620
  • 1
  • 4
  • 13
0
constructor(props) {
    super(props);
    this.state = {
      username: "",
      age: "",
    };
  }

  changeHandler = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  render() {
    return (
      <div>
        <input
          type="text"
          name="username"
          value={this.state.username}
          onChange={this.changeHandler}
        />
        <input
          type="text"
          name="age"
          value={this.state.age}
          onChange={this.changeHandler}
        />
      </div>
    );
  }
Mahdi Sheibak
  • 620
  • 1
  • 4
  • 13
  • I dont I explained it well. You see you hard coded username:"" and age:"" I want the system to be able to add these based on the forms automatically. without hard coding like password:"". Like having an empty state with nothing and adding the new values as you handle onChange. – Evren Bingøl Dec 18 '20 at 15:16
  • If you have a lot of form input you have to generate these fields. And also assumption is name of these input field are not generated like name_1 name under_2. So you cant do reflection on the object. So Only way I think is creating an empty state and adding the keys on onChage if they are not in there by preserving the old state. – Evren Bingøl Dec 18 '20 at 15:19