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.
-
- private handleChange(e) {
- let change = {};
- change[e.target.name] = e.target.value;
- this.setState(change);
- }
Usage: Define the state variables in your
ITestState.ts file as shown below
- export interface ITestState{
- CustomerAddress?: string;
- CustomerContact?: string;
- CustomerPhoneNo?: string;
- CustomerEmail?: string;
- }
Import your
ITestState.ts file to your
.tsx file
- import { ITestState } from '../ITestState';
Initialize your state variable in your
.tsx file under constructor.
- this.state = {
- CustomerAddress:' ',
- CustomerContact:' ',
- CustomerPhoneNo:' ',
- CustomerEmail:' ',
- }
Add the Office UI Fabric TextField controls to your
.tsx file as shown below.
- <TextField
- multiline
- label="Address :"
- id="Address"
- name="CustomerAddress"
- autoAdjustHeight
- value={this.state.CustomerAddress}
- onChange={this.handleChange.bind(this)}
- />
Note - the "
name" attribute in your TextField control should be same as the state variable declared.
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)}
- />
Customer Phone No- <TextField
- label="Phone Number :"
- id="PhoneNumber"
- name="CustomerPhoneNo"
- autoAdjustHeight
- value={this.state.CustomerPhoneNo}
- onChange={this.handleChange.bind(this)}
- />
Customer Email- <TextField
- label="Email Address :"
- id="EmailAddress"
- name="CustomerEmail"
- autoAdjustHeight
- value={this.state.CustomerEmail}
- onChange={this.handleChange.bind(this)}
- />
You can furthur, extend the change event to perform other operations as per your requirements:
Extended onchange event,
- private handleChange(e) {
- let change = {};
- change[e.target.name] = e.target.value;
- this.setState(change);
-
-
- if(e.target.name == "CustomerEmail"){
- this.setState({CustomerEmail : "[email protected]"});
- }
- }
Please feel free to share your comments.