ReactJS – Class, Call Properties, and Methods

In this guide, you will see examples of how a class creates and call its properties and methods. Class is a blueprint of objects. You can inherit any number of classes into child class and enhance functionality. Let’s have a look at the below example of classes that show how to create a class.

Example:

class Person{

name = 'Blogindices';  //property
call = () =>{...}    // method

}

Name is a variable/property and call is a function of Person class. If you want to call property and methods then you need to write below code.

const pers = new Person();
Pers.name; //property call
Pers.call();  // method call

The class extends can be do like below and in that case you need to use extends keyword to extend master class.

class Person extends parentClass{
}

Let’s have a look a complete example for react class and inherit master class.

React Class Example

Class Person{

	constructor(){
	  this.name = 'blogindices'; 
	}

	primntname(){
		console.log(this.name);
	}

}

const permynm = new Person();
permynm.primntname();

ReactJs Class Inheritance Example

Class Master{

	constructor(){
	  this.gender = 'male'; 
	}

	primntmae(){
		console.log(this.gender);
	}

}

Class Person extends Master{

	constructor(){
	super();
	  this.name = 'blogindices'; 
	}

	primntname(){
		console.log(this.name);
		console.log(this.gender);
	}

}

const permynm = new Person();
permynm.primntname();
permynm.primntmae();

ES7 Remove Constructor And This Keyword

In the latest javascript ES7 you can remove this keyword like below example and this is a morden javascript approch. Let’s see the previously done example with ES7.

Class Master{

       gender = 'male';

	primntmae = () =>{
		console.log(this.gender);
	}

}

Class Person extends Master{

 
	  name = 'blogindices';  

	primntname = () =>{
		console.log(this.name);
		console.log(this.gender);
	}

}

const permynm = new Person();
permynm.primntname();
permynm.primntmae();

Here still we are using this keyword in method becasue that represent current function.

Hope you are understanding about the classes, their calling process, and how to use class to show output for properties and methods. If you are looking for more class-based React web app examples, you can join us on our FB social page.

Stay in touch. Ask Questions.
Lean on us for help, strategies and expertise.

Leave a Reply

Your email address will not be published. Required fields are marked *