Home > OS >  Why square brackets used while creating dynamic state
Why square brackets used while creating dynamic state

Time:06-12

I was following a tutorial and it used square brackets for updating the state in changeHandler function for [e.target.name]. Why do we have to use square brackets with e.target.name which is just a key of the state object. I tried using the e.target.name without square brackets but it's showing me an error. Why is that so can someone please explain?

constructor(props) {
        super(props)

        this.state = {
            userid: " ",
            title: " ",
            body: " "

        }
    }

    changeHandler = (e) => {
     this.setState({ [e.target.name]: e.target.value })  // why we have used [ ] with e.target.name
        console.log(this.state)
        console.log([e.target.name])
    }

 

    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <div>
                        <label>UserId</label>
                        <input type="text" value={this.state.userid} name="userid" onChange={this.changeHandler}></input>
                    </div>

                    <div>
                        <label>Title</label>
                        <input type="text" value={this.state.title} name="title" onChange={this.changeHandler}></input>
                    </div>

                    <div>
                        <label>body</label>
                        <input type="text" value={this.state.body} name="body" onChange={this.changeHandler}></input>
                    </div>
<button type='submit'>Submit</button>
                </form>
            </div>
        )
    }
}

CodePudding user response:

Inside a object literal, when square brackets are used as a key, it tells javascript that the key is the value of the variable inside the brackets.

Ex.:

const key = 'name';

const person = {
  [key] = "John"
}

// Since key is a variable inside squared brackets, 
// javascript will evaluate its value as the key

// Therefore, the `person` object becomes:

{
  'name': 'John'
}

CodePudding user response:

The square bracket is used to get the name of the event target and set the value to the state.

  • Related