Showing posts with label get and set TextField value in react. Show all posts
Showing posts with label get and set TextField value in react. Show all posts

Thursday, 22 January 2026

How to get and set TextField value in react


How to get and set TextField value in react spfx webpart ?

1.      Add React Webpart
2.      Once your webpart is ready then open .tsx file from component folder and  Import react component module  in your webpart
import {Label, TextField} from 'office-ui-fabric-react';
3.      Check below code step by step to get and set textfield state in react



import * as React from 'react';
import styles from './ReactDemo.module.scss';
import { IReactDemoProps } from './IReactDemoProps';
import { escape } from '@microsoft/sp-lodash-subset';

//step1 import fabric react module, add label and textfield refrence
import {Label,TextField} from 'office-ui-fabric-react';
//step2 create a interface for controls
export interface IControls
{
  FirstName:string;
  LastName:string;
}
//step3 replace IControls Interface with {}
export default class ReactDemo extends React.Component<IReactDemoProps,IControls> {
  //step4 add a constructor
constructor(props)
{
  //step5 define the super method
  super(props);
  //step6 intialize control state to set the default value on page load
  this.state={
    FirstName:"Mohammed",
    LastName:"Waseem"
  };

  //step9 bind event onchange
  this.FirstNameonchanged=this.FirstNameonchanged.bind(this);
  this.LastNameOnChanged=this.LastNameOnChanged.bind(this);
}

//step7 and 10 add controls in render method
  public render(): React.ReactElement<IReactDemoProps> {
    return (
      <div className={ styles.reactDemo }>
        <div className={ styles.container }>
          <div className={ styles.row }>
            <div className={ styles.column }>
              <Label className={styles.label}>FirstName</Label>
              <TextField value={this.state.FirstName} onChanged={this.FirstNameonchanged}></TextField>
              <Label className={styles.label}>LastName</Label>
              <TextField value={this.state.LastName} onChanged={this.LastNameOnChanged}></TextField>
            </div>
          </div>
        </div>
      </div>
    );
  }


Result1: default value on page load




  //step8 to set the state value on changed in textfield
  private FirstNameonchanged(firstname:any)
  {
    this.setState({FirstName:firstname});
    console.log("FirstName state value is : "+this.state.FirstName);
  }
  private LastNameOnChanged(lastname:any)
  {
    this.setState({LastName:lastname});
    console.log("LastName state value is:"+this.state.LastName);
  }
}

Result 2 :Changed value