As a beginner with React, I found myself creating many, very similar, onChange handlers for text fields in order to achieve data binding using state. I would often look something like this:onFieldNameChange = (e) = { this.setState({ firstName: e.target.value });}onLastNameChange = (e) = { this.setState({ lastName: e.target.value });}/* continue for every text field... */But what I noticed about these handlers was that I was often writing the exact same code, with only a different field name for updating state.So I began to wonder: Is it possible to write only one generic onChange handler to use for all text fields?The answer: Yes!In the snippet above, we use e.target.value to get the new value of the text fields in order to update state, but we can also use target get other useful data. In this example, we also access name from the e.target and use it as a key when calling this.setState in our onChange handler:class Form extends Component { state = { firstName: '', lastName: '', /* Initialize all text fields with empty strings.
I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.
Stay tuned to my blog, twitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.
coding,web-development,javascript,react,front-end-development
Stay tuned to my blog, twitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.
This article is related to
coding,web-development,javascript,react,front-end-development
0 Comments