-->

10/11/2017

React Component Basics

For this post , i assume you are familiar with basics of SharePoint framework development, using yoman templates , node package manager and gulp. Else please refer to my earlier post Basics of SPFX

Sharepoint Framework (SPFX) is becoming popular as it is the only way to add custom functionality to a Sharepoint Online modern pages.

We can integrate any java script framework to work with SPFX. In last post we did integrate Angular with SPFX.  But, we need to do everything from scratch like importing packages and then adding them in config files, etc.

REACT is one of the java script framework which comes with yoman scaffold out of the box. So the installation, references and default code were taken care by yoman generator. React got lot of plugin support and its consistently improving by each version.

So REACT became a mandatory component to learn for SPFX development.
REACT coding is mostly dealing with properties and state on client side. 
For this we have 2 types of components in REACT.

1.Function Component : 

Basically function component deals with properties only. It has no state.
For example if you create a new SharePoint Framework (SPFX) solution for a webpart and select React as the java script template, this is what you get in your component (.tsx) file.


Look at that, this component accepts properties and renders markup (JSX) using those properties. It has nothing to deal with state. If the properties are changed, the function component will re-render.
If you want to check this, the OOTB code comes with a property description. If you edit the property, you can see that the markup is re-rendered immediately.


2. Class Component:

Now class component will accept both properties and state elements and renders JSX / markup.
I have created a example component for our better understanding. I wrote the comments which are self explanatory in the image itself.


One important thing to note here is that a class component will re-render when its state is changed. So in the above example when we call "addNewList" method and update the state , the class component will re-render the view.

I have updated the "ExampleComponent.tsx" file to make it workable with default webpart code.
Also updated the webpart.ts file to display Our "Example Component" instead of  default function component.


Finally here is the output of our class component.


When the button is clicked, even though no properties changed, the state is updated. Thus the class component will render again.



Don't worry about the screenshots, i have attached the zip file of the src folder for your reference.

Download the code from this  link.
Source Code

Please note that i have zipped only src folder and not entire solution . So you can generate any text project with yoman generator and check my files for reference.

Check the "React Component Lifecycle", my next article here.

No comments:

Post a Comment