Introduction
In this blog, we will learn to use a single change function which holds multiple textfield values to its respective state variable in SharePoint Framework (SPFx)
The onchange event occurs when the value of an element has been changed.
Steps Involved
Below is the onchange function that is used for multiple textfield controls.
- /*this is to capture the values of all text boxes and store in their respective state variables*/
- private handleChange(e) {
- let change = {};
- change[e.target.name] = e.target.value;
- this.setState(change);
- }
- export interface ITestState{
- CustomerAddress?: string;
- CustomerContact?: string;
- CustomerPhoneNo?: string;
- CustomerEmail?: string;
- }
- import { ITestState } from '../ITestState';
- this.state = {
- CustomerAddress:' ',
- CustomerContact:' ',
- CustomerPhoneNo:' ',
- CustomerEmail:' ',
- }
- <TextField
- multiline
- label="Address :"
- id="Address"
- name="CustomerAddress"
- autoAdjustHeight
- value={this.state.CustomerAddress}
- onChange={this.handleChange.bind(this)}
- />
For example: In the above control "CustomerAddress" is used as a values for the "name" attribute and also it is decalared as state variable.
This change event can be extended to all the controls which have a name attribute.
Similarly, you can use this for multiple controls as shown below:
Customer Contact
- <TextField
- label="Customer Contact :"
- id="CustomerContact"
- name="CustomerContact"
- autoAdjustHeight
- value={this.state.CustomerContact}
- onChange={this.handleChange.bind(this)}
- />
- <TextField
- label="Phone Number :"
- id="PhoneNumber"
- name="CustomerPhoneNo"
- autoAdjustHeight
- value={this.state.CustomerPhoneNo}
- onChange={this.handleChange.bind(this)}
- />
- <TextField
- label="Email Address :"
- id="EmailAddress"
- name="CustomerEmail"
- autoAdjustHeight
- value={this.state.CustomerEmail}
- onChange={this.handleChange.bind(this)}
- />
Extended onchange event,
- private handleChange(e) {
- let change = {};
- change[e.target.name] = e.target.value;
- this.setState(change);
- /** to set default email to Email state variable */
- if(e.target.name == "CustomerEmail"){
- this.setState({CustomerEmail : "[email protected]"});
- }
- }
Please feel free to share your comments.
Hope this helps!

Join the conversation! Your thoughts help the community grow.