React - Learn From Scratch - Part Five

Introduction 
 
What we’ll learn in this part:
Before we proceed any further with React, we need to understand some JavaScript concepts/constructs. I know this article is about React, but a good understanding of these concepts will not make you confused while trying to understand the existing React code. You may skip any section if you are already knowledgable in the concept.

Classes in JavaScript

JavaScript is a functional programming language i.e. everything is a function. If we want to do Object Oriented Programming in it, we still use functions to achieve class-like behavior. Prototypal inheritance exists to achieve OOP inheritance. We’ll not go into more details of it. If you don’t know how this works, don’t worry, this understanding is not required for React.
 
Before ES6 (ECMAScript2015), the class keyword does exist in JavaScript but just as a reserved keyword. In ES6, classes are introduced. But it is just syntactical sugar coating over existing prototype-based inheritance. It means behind the scenes, no new model is introduced in JavaScript. In short, we can create classes in JS as we do in other OOP languages (e.g. C#, Java). Every new version of ES introduces new features to classes.
 
In the following example, we are creating a Person class which has three properties (id, name & age). Then we’ve created the ‘Employee’ class which is inheriting the ‘Person’ class. Open a page in your browser and check the output on the console.
  1. <html>    
  2. <head>    
  3. </head>    
  4. <body>    
  5.     <script >    
  6.         class Person {    
  7.             id =0; //with initialization    
  8.             name;  //without initialization    
  9.             constructor(i,n,a){    
  10.                 this.id = i;    
  11.                 this.name = n;    
  12.                 this.age = a; //will become part of instances    
  13.             }    
  14.     
  15.             show(){    
  16.                 console.log('ID is:' + this.id);    
  17.                 console.log('Name is:' + this.name);    
  18.                 console.log('Age is:' + this.age);    
  19.             }    
  20.     
  21.             //Function with 'function keyword'    
  22.             show2 = function(){    
  23.                 console.log('valid function');    
  24.             }    
  25.         }    
  26.     
  27.         //obj will have three properties (id,name & age)    
  28.         var obj = new Person(1,"Bilal",100);    
  29.         obj.show();    
  30.         obj.show2();    
  31.     
  32.         class Employee extends Person {    
  33.             constructor(i,n,a,comp){    
  34.                 super(i,n,a);    
  35.                 this.company = comp;    
  36.             }    
  37.             show(){    
  38.                 super.show(); //call parent show method    
  39.                 console.log('Company is:' + this.company);    
  40.             }    
  41.         }    
  42.         console.log('--------------------');    
  43.         var emp = new Employee(2,"Bilal S",100,'LearningInUrdu.pk');    
  44.         emp.show();    
  45.     </script>    
  46. </body>    
  47.      
  48. </html>    
Here are some quick points regarding JS classes. For more detail, check out this link.
  1. We create a class by using the ‘class’ keyword like we do in C# or Java. 
  2. No keyword is required to declare a variable. The ‘function’ keyword can be skipped to declare a function in class.
  3. The ‘this’ keyword is the same as we’ve seen in other languages. It represents the caller.
  4. We create an instance of a class by using the ‘new’ keyword as we do in C# or Java.
  5. A function with the name ‘constructor’ is a special function. Its concept is the same as we’ve in other languages. In JS, we can have only one such function in class.
  6. Class data members can be declared inside the constructor or outside the constructor. Declaration can be with or without initialization.
  7. We can have static functions & static data members like we’ve in other languages.
  8. We can inherit other classes by using extends keyword like we do in Java. If we have a constructor in the child class, its first statement should be called to ‘super()’ function. ‘super()’ function executes parent class constructor.
  9. To call the function of the parent class, ‘super’ keyword can be used (e.g. super.Show())

Should we start using classes now?

 
Yes & No. classes are introduced in ES6 so before using classes (or any internal feature e.g. static or private data members), we need to check if a browser supports this feature or not. OR we may use transpilers (e.g. TypeScript or Babel) which allow us to use the latest features and then allow us to convert our code into an older version of ECMAScript if required. 

‘this’ operator

“this” inside a function represents a “caller”. If a function is part of an object, we can call that function using dot (.) notation (e.g. myObj.Show()). In this case, “this” inside “Show” function represents (or alias of) “myObj” object. We can use different callers for a function by using ‘call’ or ‘apply’ methods. Flexibility to have different callers of the same function is a powerful feature but sometimes we don’t want this.
  1. <script >  
  2.         var obj ={  
  3.             a: 10,  
  4.             show: function(){  
  5.                 alert('value of a is:' + this.a);  
  6.             }  
  7.         }  
  8.   
  9.         //'this' refers to 'obj' and 'obj' has a = 10  
  10.         obj.show(); //output will be: '10'  
  11.   
  12.         //func now points to same show function  
  13.         var func = obj.show;  
  14.   
  15.         var obj2 = {  
  16.             a:20  
  17.         }  
  18.         //we can call a function using 'call' method by passing the 'caller' as parameter  
  19.         //Here we are calling 'func' or 'show' function with context of 'obj2'  
  20.   
  21.         func.call(obj2); //output will be: '20' as 'this.a' means 'obj2.a';  
  22.   
  23.     </script>  
Here is the same example of ‘this’ using classes
  1. <script >  
  2.         class Person{  
  3.             a = 10;  
  4.             constructor(){  
  5.             }  
  6.             show(){  
  7.                 console.log('value of a is:' + this.a);  
  8.             }  
  9.         }  
  10.   
  11.         var obj = new Person();  
  12.         //'this' refers to 'obj' and 'obj' has a = 10  
  13.         obj.show(); //output will be: '10'  
  14.   
  15.         //func now points to same show function  
  16.         var func = obj.show;  
  17.         func(); //Error as 'this' is undefined  
  18.   
  19.     </script>  
Sometimes we want to use a “predefined” object for “this” irrespective of caller. There are multiple ways of doing this. We'll see those in the next article.

React Class Component

We’ve learned about the Function component earlier. Let see how we can create a class component. In the following example, we’ve converted our ‘Profile’ component to the class component. Both approaches are given for learning purposes. Remember ‘React Class Component’ is just a class which we’ve discussed at the start of this article.
  1. <script type='text/babel'>  
  2.   
  3.         //Creating a Function Component  
  4.         function Profile(props){  
  5.             return (  
  6.                 <div class="mycontainer" >  
  7.                     <h3>{props.name}</h3>  
  8.                     <a href={props.url}>{props.urlText}</a>;  
  9.                 </div>  
  10.                 );  
  11.         }  
  12.           
  13.         //Creating a Class Component  
  14.         class Profile extends React.Component{  
  15.               
  16.             constructor(pro){  
  17.                 super(pro);                  
  18.             }  
  19.             render(){  
  20.                 return (  
  21.                 <div class="mycontainer" >  
  22.                     <h3>{this.props.name}</h3>  
  23.                     <a href={this.props.url}>{this.props.urlText}</a>;  
  24.                 </div>  
  25.                 );  
  26.             }  
  27.         }  
  28.   
  29. </script>  
  1. A class component is a class that is inheriting React.Component class
  2. In the React instance of our component, it passes ‘props’ to the constructor. We must call super() as the first statement. If we miss this call, we'll get an error. Writing a constructor function is optional. 
  3. React creates 'props' as class member so we can access it by using 'this.props' anywhere.
  4. We’ve moved our component UI part in the ‘render()’ method. As ‘props’ data is not available in this function but available in class level property, we need to access it using ‘this’.
  5. Also, it is not required to have all components of one type (e.g. Function component or class component)
In the following example, we’ve converted ‘Profiles’ component using class components. Changes are the same that we have seen while converting the ‘Profile’ component. Both approaches are given for learning purposes.
  1. <script type='text/babel'>  
  2. function Profiles(props){  
  3.             var profilesElem = props.data.map(  
  4.                     (obj)=>(  
  5.                         <Profile   
  6.                         key={obj.id}   
  7.                         eid={obj.id}   
  8.                         name={obj.name}   
  9.                         url={obj.url}   
  10.                         urlText={obj.urlText}   
  11.                         />)  
  12.                 );  
  13.             return profilesElem;  
  14.         }  
  15.   
  16.     class Profiles extends React.Component{  
  17.             //We've removed constructor intentionally  
  18.             render(){  
  19.                 var profilesElem = this.props.data.map(  
  20.                     (obj)=>(  
  21.                         <Profile   
  22.                         key={obj.id}   
  23.                         eid={obj.id}   
  24.                         name={obj.name}   
  25.                         url={obj.url}   
  26.                         urlText={obj.urlText}   
  27.                         />)  
  28.                 );  
  29.             return profilesElem;  
  30.             }  
  31.         }  
  32.   
  33. </script>  
In following example, we’ve converted MyApp component.
  1. <script type='text/babel'>  
  2. function MyApp(){  
  3.               
  4.             //hard coded data for now  
  5.             var data = [  
  6.                 {id: 1, name:"Bilal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials"},  
  7.                 {id: 2, name:"Faisal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 2"},  
  8.                 {id: 3, name:"Waqas Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 3"},  
  9.                 {id: 4, name:"Khurram Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 4"}  
  10.                 ];  
  11.               
  12.             return (  
  13.                 <div class="maincontainer">  
  14.                     <Profiles data={data} />  
  15.                 </div>  
  16.             );  
  17. }  
  18.   
  19. class MyApp extends React.Component{  
  20.             data = [  
  21.                 {id: 1, name:"Bilal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials"},  
  22.                 {id: 2, name:"Faisal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 2"},  
  23.                 {id: 3, name:"Waqas Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 3"},  
  24.                 {id: 4, name:"Khurram Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 4"}  
  25.                 ];  
  26.             
  27.             render(){  
  28.                 return (  
  29.                 <div class="maincontainer">  
  30.                     <Profiles data={this.data} />  
  31.                 </div>  
  32.             );  
  33.             }  
  34.         }  
  35.     </script>  
Here is a full example with class components. Note that the event handling code is removed intentionally to keep things simpler.
  1. <script type='text/babel'>  
  2.         class Profile extends React.Component{  
  3.             constructor(pro){  
  4.                 super(pro);
  5.             }  
  6.             render(){  
  7.                 return (  
  8.                 <div class="mycontainer" >  
  9.                     <h3>{this.props.name}</h3>  
  10.                     <a href={this.props.url}>{this.props.urlText}</a>;  
  11.                 </div>  
  12.                 );  
  13.             }  
  14.         }  
  15.   
  16.         class Profiles extends React.Component{  
  17.              
  18.             render(){  
  19.                 var profilesElem = this.props.data.map(  
  20.                     (obj)=>(  
  21.                         <Profile   
  22.                         key={obj.id}   
  23.                         eid={obj.id}   
  24.                         name={obj.name}   
  25.                         url={obj.url}   
  26.                         urlText={obj.urlText}   
  27.                         />)  
  28.                 );  
  29.             return profilesElem;  
  30.             }  
  31.         }  
  32.   
  33.         //Created a top level component  
  34.         class MyApp extends React.Component{  
  35.             data = [  
  36.                 {id: 1, name:"Bilal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials"},  
  37.                 {id: 2, name:"Faisal Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 2"},  
  38.                 {id: 3, name:"Waqas Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 3"},  
  39.                 {id: 4, name:"Khurram Shahzad",url:"https://www.youtube.com/c/LearnInUrdu139",urlText:"Learn in Urdu Tutorials 4"}  
  40.                 ];  
  41.               
  42.             render(){  
  43.                 return (  
  44.                 <div class="maincontainer">  
  45.                     <Profiles data={this.data} />  
  46.                 </div>  
  47.             );  
  48.             }  
  49.         }  
  50.   
  51.         ReactDOM.render(<MyApp />,document.getElementById('app'));  
  52.     </script>  
Now let’s add some buttons to ‘Profile’ component and show an alert when button is clicked. We’ll notice that first two buttons will be throwing exception on console but third button click is working fine. Can you guess? We’ll check this in next article as it requires more understanding of the 'this' operator.
  1. <script type='text/babel'>  
  2.         class Profile extends React.Component{  
  3.              
  4.             CountClickHandler(e){  
  5.                 //What is 'this' here?  
  6.                 alert(this.props.eid);  
  7.             }  
  8.             render(){  
  9.                 return (  
  10.                 <div class="mycontainer" >  
  11.                     <h3>{this.props.name}</h3>  
  12.                     <a href={this.props.url}>{this.props.urlText}</a>  
  13.                     <button onClick={function(){alert(this.props.eid);}} >Count Me In 1</button>  
  14.                     <button onClick={this.CountClickHandler} >Count Me In 2</button>  
  15.                     <button onClick={()=> {this.CountClickHandler()}} >Count Me In 3</button>  
  16.                 </div>  
  17.                 );  
  18.             }  
  19.         }  
  20. </script>  
If you have any questions or suggestions to improve this article, don't hestiate to share. 

Summary

We basically learned another type of component i.e. class components. Both types of components receive 'props'. To understand it in a better way, we learned about classes in JavaScript. 
 
Links for more reading:
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
  • https://hacks.mozilla.org/2015/07/es6-in-depth-classes/