Created
November 7, 2019 14:26
-
-
Save joe-oli/510f24e9fd0347d64afbc0b2478027ba to your computer and use it in GitHub Desktop.
Square brackets in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
What do square brackets [] around e.target.name mean? | |
this.setState({ [e.target.name] : e.target.value}); | |
Instead of this: | |
<input type="text" name="title" onChange={this.onTitleChange} value={this.state.title} /> | |
<input type="text" name="address" onChange={this.onAddressChange} value={this.state.address} /> | |
<input type="text" name="description" onChange={this.onDescriptionChange} value={this.state.description} /> | |
onTitleChange (e) { | |
this.setState({ title : e.target.value}); | |
} | |
onAddressChange (e) { | |
this.setState({ address : e.target.value}); | |
} | |
onDescriptionChange (e) { | |
this.setState({ description : e.target.value}); | |
} | |
We can write JUST ONE handler like this: | |
<input type="text" name="title" onChange={this.onChange} value={this.state.title} /> | |
<input type="text" name="address" onChange={this.onChange} value={this.state.address} /> | |
<input type="text" name="description" onChange={this.onChange} value={this.state.description} /> | |
onChange (e) { | |
this.setState({ [e.target.name] : e.target.value}); | |
} | |
You are accessing the state Obj's property using array-syntax, instead of prop-syntax; | |
PROVIDED you designed the state Obj to contain exactly each html form element (tag)'s `name` attribute as the Obj.prop | |
i.e. in this case your state Obj would look like | |
this.state = { | |
title: '', | |
address: '', | |
description: '', | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment