SPFx React Basics & Life-Cycle

In this post we will see some basic concepts about below topics.
  • React Intro
  • React Vs Angular
  • React Life-Cycle
  • Virtual DOM
  • Create React Solution
  • Difference between No Framework vs React Solution
  • Components (.tsx file)
  • Elements
  • Props
  • State
  • React Events
  • React Events-Passing parameters
  • Arrow method

React Intro:

    React is a JS Library, Used to build User Interface.
    It is developed & Maintained by Facebook
    We will use React as V in MVC, SPFx provides its own model & controller


React Vs Angular

Angular

React

It's a Framework

Its a JS Library

Its a MVC model

React gives only V

Bi-directonal data flow

One way data flow

Dependency Injection supported

Dependency Injection not supported



React Life-Cycle(Link1,Link2)

  •     Three phases of React Life Cycle: 
    • Mounting =>  Putting elements into the DOM
    • Updating => Whenever there is a change in the component's state or props
    • Unmounting => When a component is removed from the DOM
  • Mounting
      1. constructor()
        • This method is called before anything else, place to set up the initial values
      2. getDerivedStateFromProps()
        • Called right before render, place to set the state object based on the initial props
      3. render()
        • This method is required & it outputs the HTML to the DOM
      4. componentDidMount()
        • Called after the component is rendered. Components added to DOM can updated here.
      • Here render() method is required and will always be called, the others are optional
    • Updating
        1. getDerivedStateFromProps()
          • First method called when component updated(Eg: any btn click), we can set the state object with initial props
        2. shouldComponentUpdate()
          • Based on our Boolean value render method will be called. (We can use this for any validations)
        3. render()
          • Re-render the HTML to the DOM, with the new changes
        4. getSnapshotBeforeUpdate()
          • Even after the update, you can check what the values were before the update with props & State (prevProps.PropName, prevState.StateName)
        5. componentDidUpdate()
          • Called after the component is updated in the DOM
      • Unmounting
        1. componentWillUnmount()
          • Called when the component is about to be removed from the DOM


      SPFx Life-Cycle

      • Note: SPFx life cycle is different with React Life cycle. Refer below methods.
      • When loading the web part on a page below methods are fired in the following order: 
        • onAfterDeserialize()
        • onInit()
        • render()
        • onBeforeSerialize()
      • When the web part is removed from a page
        • onDispose()
      • For SPFx webpart property pane we have different set of methods
      • Opening the property pane:
        • Opening the property pane:
        • loadPropertyPaneResources()
        • getPropertyPaneConfiguration()
        • onPropertyPaneRendered()
        • onPropertyPaneConfigurationStart()
      • Updating the properties in the property pane
        • onPropertyPaneFieldChanged()
        • render()
        • getPropertyPaneConfiguration()
        • onPropertyPaneRendered()
        • onPropertyPaneConfigurationComplete()
      • Refer this link for more details Link

      Virtual DOM:

      • DOM- Document Object Model (It Represent UI)
      • In actual DOM whenever changes done all elements will get loaded which affect performance.
      •  In React it maintains 2 versions of existing DOM. 1st version is replica of actual DOM & 2nd     version created whenever any change in actual DOM. React will compare both version and   update only the new change to the actual DOM

      Create React Solution:

               Create new folder(ReactCRUD) for solution manually or using cmd prompt.
                     Create Folder:  md ReactCRUD 
                     Open Folder:  cd ReactCRUD 





                Type the below yeoman comment to create spfx component using yeoman.
                                               yo @microsoft/sharepoint


      Provide the details for solution name, webpart name, etc... & Select template as React.


      Open solution in Visual Studio Code

              Now we have to open the folder using visual studio code.(or Enter "code ." in cmd prompt it automatically opens this solution in VS Code)

      Difference between No Framework vs React Solution:
      1.  React Solution create "Components" inside webpart folder.


      2. 'No Framwork': Code added under webpart  render() Method.
            (src\webparts\webpart.ts)
      'React': Code added  under component render() method.
            (src\webparts\components\webpartName.tsx)
      Later it will rendered to webpart render() method using  ReactDom.render(element, this.domElement);


      Understand important Concepts & Files 
      Components (.tsx file):
          Components are JavaScript functions(modules) which will accept inputs(props) & display outputs based on the requirement. (Ex. src\webparts\components\name.tsx file)


      Elements:
          What we get returned from components is call it as Elements. Elements added in webpart.ts render method (src\webpart\webpart.ts) using  ReactDom.render(element, this.domElement)



      Props:
          Props are used to pass data to the components. Properties are read only. 
      Components properties are declared in src\webparts\components\IProps.ts file.

       Props values are assigned in src\webpart\webpart.ts file

       Props values are used in components (src\webparts\components\name.tsx)

      State:
          State is a object used to store property values of components. Since Props is only read only so we need something to updated values dynamically(Not Read Only).
      1.To create Interface for state:
      Components folder right click>New File> Type "IAnyNameState.ts".  Now add interface code in this file and add state properties to use.
      2.To use this State object: 
          In component(.tsx) file & 
              i)Import state 
              ii)Add state parameter to render method
              iii)Add constructor to assign initial value 
              iv)Use state object in code using {this.state.propertyName} keyword       

               v)Update state: this.setState({propertyName:"value"})
      Note: Update State object will automatically call .tsx render method. So never change the state of the component(.tsx) inside render method, it will lead to deadlock)




      React Events

      •     React can perform events based on click, change, mouseover, etc...
      •     Event  written in curly braces onClick={methodName}
      •     React events follows caml casting
          Sample Code:
          src\webpart\components\.tsx file

          class TestClassName extends React.Component{
      test(){
      alert("Hello");
      }
          render(){
      return{
      <button onClick={this.test}>Test the Method </button>
      }
          }

          src\webparts\webpart.ts file:
          ReactDom.render(element, this.domElement);


      React Events-Passing parameters:
         We can pass arguments in 2 different ways
         1.Using normal binding method     
                  Comparison with Normal Method:
                  For regular methods we should bind using this keyword in constructor of the                                           component 
                  "this" represents object which called the function(ex. windows, button click etc)
                          
                          <button onClick={this.testMethod(this,"Hello")}></button>
                           Add binding in Constructor
                           this.testMethod = this.testMethod.bind(this);
                           Sample method
                           testMethod(ev, value:string){
              alert("Hello");
                           }


         2. Arrow method:  
                          For arrow methods we no need to bind explicitly  using this keyword in constructor of                            components
                          In Arrow function "this" represents object that is defined in the arrow function                  
                        
                            <button onClick={()=>this.testMethod("Hello")}></button>
                            
                            testMethod=(value:string)=>{
              alert(value);
                            }
                            
                           passing object
                           <button onClick={(ev)=>this.testMethod("Hello", this)}></button>

                         testMethod=(value:string, ev)=>{
              alert(value);
                            }





      Please refer this video for more details.


        Comments

        Popular posts from this blog

        Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

        A type named 'SP.Data. could not be resolved by the model error

        Add content type to SharePoint List/Library using REST API