Paul
Paul

Reputation: 271

Best way to set state of object using dynamic key name? - reactjs

I have a react state like:

this.state = {
  formInputs: {
    username: '',
    password: '',
    passwordConfirm: '',
  },
  handleChange = () => {
    const {target: {name, value}} = event;
    this.setState({
      [name as keyof formInputs]: value
    });
  }
};

How can I change this line ( [name as keyof formData]: value) to a JavaScript instead of Typescript?

Upvotes: 1

Views: 1327

Answers (3)

joy08
joy08

Reputation: 9652

We can use Computed property names concept to compute the object property name dynamically. For that we need to put the expression inside [].

When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

For your state

this.setState({
    formInput: {
        ...this.state.formInput,
        [event.target.name]: event.target.value
    }
})

Sandbox for your reference: https://codesandbox.io/s/react-basic-example-p7ft8

import React, { Component } from "react";

export default class Login extends Component {
  state = {
    formInputs: {
      email: "",
      password: ""
    }
  };

  handleOnChange = event => {
    this.setState({
      formInput: {
        ...this.state.formInput,
        [event.target.name]: event.target.value
      }
    });
  };

  render() {
    return (
      <form>
        <label>Email</label>
        <input type="text" name="email" onChange={this.handleOnChange} />
        <label>Password</label>
        <input type="password" name="password" onChange={this.handleOnChange} />
      </form>
    );
  }
}


Upvotes: 4

sourav satyam
sourav satyam

Reputation: 986

I think you can initialize your formObject as empty json and

this.state = {formInput: {}}

Later onChange you can set the value something like

this.setState({formInput[event.target.name]: event.target.value})

and conditionaly check if (this.state.formInput.username) ? this.state.formInput.username : '' to value

Upvotes: 0

Burak Gavas
Burak Gavas

Reputation: 1354

You can directly use Bracket_notation

[name]: value

In your case, { formInput: { username:"", password: "" }

this.setState({
    formInput: {
        ...this.state.formInput,
        [name]: value
    }
});

Upvotes: 2

Related Questions