React class based component
Table of Contents
Published on
It has been 2 weeks, that I am working with javascript ecosystem. I observed JS world is not leaned towards Classes (or OOP). I thought to get taste of classes in Javascript In javascript classes behave differently than other languages like Python and Ruby or C++.
Note: In react, class components are deprecated, but will not be removed. I am showing this for learning purpose.
Javascript class
classmethods do no need function keyword- Constructor method is called
constructor()
class Person {
constructor() {
// sprinkle code here
}
greet() {
console.log("Hey I belong to person class");
}
}
- Javascript people call class variable “field”. Field is initialzed without
letorconst. If you so, it will throw error. - Instance field
class Person {
constructor () {
this.name = "John Doe"; // name is field
}
}
- Instance field outside of constructor
class Person {
name = "John";
constructor () {
// sprinkle code here
}
}
Now we can proceed to react class components.
React class component
- React class component inhert from React.Component class.
import React from "react"
class MyComponent extends React.Component {
// code
}
- In class you cant use hooks like
useState, you do, specify instance fieldstateoutside constructor
import React from "react"
class MyComponent extends React.Component {
state = { count: 0 }
// ...
}
- Html content is returned by method
render()
import React from "react"
class MyComponent extends React.Component {
state = { count: 0 }
render() {
return (
<h1> Count is {this.state.count}</h1> // accessing state
);
}
}
- What about modifying state? by default react class provides method
this.setState()to change value of state
import React from "react"
class MyComponent extends React.Component {
state = { count: 0 }
increment() {
// updating value by 1
this.setState( prev => prev.count + 1);
}
render() {
return (
<h1> Count is {this.state.count}</h1> // accessing state
);
}
}
Note:
In class component, state must be only in one variable i.e state
To store multiple data, use this.state = { data1: ... , data2: ... }
When updating state, each key retain its old values, unless you modify that too
import React from "react"
class MyComponent extends React.Component {
state = { data1: 10, data2: 0 }
updateData() {
this.setState( {data1: 100} ); // here data2 will retain value of 0
}
render() {
return (
<h1> Count is {this.state.count}</h1> // accessing state
);
}
}
Related Posts