0

I know there are a whole lot of questions on square brackets in javascript - however, I did not get an answer to my requirement


class SignIn extends Component{

    constructor(props){
        super(props);

        this.state = {
            email: '',
            password: ''
        }
    }

    handleSubmit = event => {
        event.preventDefault();
        this.setState({"email" : '', "password" : ''});
    };

    handleChange = event => {
        const {value, name } = event.target;
        this.setState({[name] : value}, () => {console.log(this.state)});
    };

    render(){
        return (
            <div className='sign-in'>
                <h2>I already have an account</h2>
                <span>Sign in with your email and password</span>
                <form onSubmit={this.handleSubmit}>
                    <label>Email</label>
                    <input name="email" type="email" ref="email" onChange={this.handleChange} value={this.state.email} required />
                    <br/>
                    <label>Password</label>
                    <input name="password" type="password" ref="password" onChange={this.handleChange} value={this.state.password} required />
                    <input type="submit" value='Submit Form' />
                </form>
            </div>
        )
    }
}

My question is more on this line - here in this code snippet;

this.setState({[name] : value}, () => {console.log(this.state)});

The square bracket is used to get the name of the event target and set the value to the state. For example, if the email field is changed - it fetches the email value and sets it to the state (state object/email value) and does the same to the password as well.

My question is this;

  • What is this called in JS/React? I need to read more and for this purpose, I'd like to know what this is called
code_kbd
  • 314
  • 2
  • 9

1 Answers1

-1

it's named Computed property name

Oboo Cheng
  • 3,155
  • 1
  • 19
  • 26
  • looks like its a duplicate question - but thanks for answering - since i could not simply "search" it to get an answer. – code_kbd Jul 05 '20 at 03:43