React Component

React Component

React components are reusable code which can be defined as a class or as function.

If React Component is class Type then, will have render method and will return JSX expression

i.e we write in the form of HTML but converted to JSX using babel compiler( That we already added in Visual Studio). If not you can check this post for setting react for local development

Note: JSX expression are html like code we write as part of return statement. This JSX expression can be assigned to variable or can be passed to function parameter. We can treat it as object. And can be passed and used where normal variables or objects can be used

React jS, Class Component

React JS enables us to define its component as a class. Most object-oriented programmers prefer Class Component of React JS over the Functional component of React JS. As they find class component to easily readable and easy to understand because of their familiarity with the Object-Oriented paradigm.

How to create React Js Class Component

Below code snippet shows the way to create Class Component in react Js.

Example of Class Component :

import React, { Component from react";
class Counter extends Component {
render() {
return World</hl+;
export default Counter;

This render method return jsx. And is compiled by bable to  something like bellow

createC1ass (Counter, [ {
key: "render " ,
value: function render ( )
return / PURE * /
react .default. createE1ement ( "hl " ,
null, "'Hello World");

Here Babble automatically identifies the tag and its create the element using js method. But Common mistake when we add add multiple tags then it gives error something like this.

In the above snippet you might have noticed that is we have render() method that returns HTML element this HTML element is actually JSX expression. In React js every class component must have a render() method that will be responsible for rendering this component to UI.

render() is the only required method for every react’s Class Component.

And also render() method should not update state of the component.

How to have Constructor in React JS

React JS uses its Constructor to initialize all properties required by component while rendering it. React calls constructor of the component only once in its entire life cycle.

Now, you would be wondering how properties passed to component should be fetched by it. Answer is simple, By using react js props.

import React, { Component } from "react";

class Counter extends Component {
  counter = 0;
  constructor(){
    this.counter = 2;
  }
  render() {
    return (
      <React.Fragment>
        <span>{this.counter}</span>
        <button> Counter </button>
      </React.Fragment>
    );
  }
}

export default Counter;

React Component Props

Some time our component requires properties to initialize itself, These properties are passed to the react component as props in this way <Counter counter=3 />.Now, counter property is passed to counter component, And can be fetched by Counter Component using react’s props attribute.

We can use a constructor in React’s class component to fetch props as shown below.

 constructor(props){
    super(props);
    this.counter = this.props.counter;
  }

OR

constructor(counter){
    super(counter)
    this.counter = this.counter;
  }

When we use constructor to fetch props then constructor should call super(props), If we miss to do that then we will run into error.

React js Component Props, Without using constructor

you can pass props directly to your’s render() method of react’s class component.

 render(props) {
    return (
      <React.Fragment>
        <span>{this.props.counter}</span>
        <button> Counter </button>
      </React.Fragment>
    );

But disadvantage of using props in render is that you won’t be initialize state with props value.

React State

In React Component of type Class you can define react state as follows. Mainly you guys need to focus on line 2-4,6

class Application extends React.Component {
  state = {
    count: 3,
  };
  constructor(props){
    super(props)
    this.state.count = this.props.count
  }
  render() {
    return <div>
      <h1>Hello, ES6 and React 0.13! {this.state.count}</h1>
      <p>
        More info <button onClick ={this.onBtnClick}>here</button>.
      </p>
    </div>;
  }
onBtnClick = () =>{
  this.setState({count: this.state.count+1})
}
}

/*
 * Render the above component into the div#app
 */
React.render(<Application count ={10}/>, document.getElementById('root'));

At line 2-4 we are declaring state element for react component.

And at line 7 we are initializing our component state. Now what we need is to update the state of the react component.

Updating React State

To update react state, React JS give us a method called setState(<object>). setState(<object>) will update the state of react js component and notifies react about change of state of the component so that react can update its component in ui .

onBtnClick = () =>{
  this.setState({count: this.state.count+1})
}

Functional Component or Stateless Component

Functional component works similar to react class component. Just here you donot have to maintain extra code for constructor or explicitly define state.

By name it is clear that React Functional Component or StateLess Component has similar structure like function as shown below

function App(){
	return <h2>Hello Functional Component </h2>;
};

OR

const App = () => {
	return <h2>Hello Functional Component </h2>;
};

Adding State to Functional Component in React Js

React js provides React.useState(). React.useState() can be used to use State in React Functional Component. The complete structure is as follow

const [count, setCount] = React.useState(10);

As you seen here

  • count: is state variable
  • setCount: is function use to update the state i.e to update state variable count
  • useState(10): Parameter of useState(10) denotes the initial value assigned to that state variable, In our cause we assigned 10 to count.

Let’s see real time use, Here we will update the state on button click.

function App() {
  const [count, setCount] = React.useState(10);
  const onBtnClick = () => {
    setCount(20);
  };
  return (
    <React.Fragment>
      <h1>HEllwo </h1>
      <button onClick={onBtnClick}>{count} - is count</button>
    </React.Fragment>
  );
}

Above, onBtnClick() at line 9 we are updating the count to 20.

Common mistakes.

  • function onBtnClick() should be declared before use otherwise it won’t be recognized.
  • we should use const keyword before function as shown on line 2 and 3 in the above code
  • When returning JSX expressions (in Class or Functional Component), if that expression contains more than one HTML tags then it should be enclosed in parent element otherwise will get bellow error.
cornponents > JS counterCornponent.jsx > Counter > render
import React, { Component from react";
class Counter extends Component {
render()
return World
JSX expressions must have one parent element.
Peek Problem (XF8) No quick fixes avaiable
ts(2657)
<button>lncrement</button>) ;
export default Counter;

JXS expression must have one parent element  as now babel is unable to identify which element to keep createElement function. There fore to resolve this we will wrap our code in separate <div> tag as shown below.

import React, { Component } fron
class Counter extends Component
render() {
return (
<button> Counter </butto

OR instead of <div> we can use react element created for this specific purpose <React.Fragment> as shown below

return
. F ragmentE
<button> Counter </bt
</React. Fraamen
class component example

State variable in above snippet defines the state.

React Lifecycle Method

React Lifecycle methods
React Lifecycle Methods

Previously we discussed every thing about component now lets discuss react lifecycle methods. React lifecycle methods can come handy, Let’s discuss some of them.

We have taken most commonly used react lifecycle method and divided it into there group i.e Mount, Update and Unmount.

Mount

Mount groups contains group of react lifecycle methods that are called during mounting phase of the react component.

Sequence of method calling is as

  1. Constructor() : Called for doing initialization of the state and other component properties.
  2. render() : this called to render component to UI
  3. componentDidMount() : componentDidMount() will be called when render is completed and your component is mounted successfully. and also invoked whenever our component is mounted i.e whenever view of the component is updated due to state changes this method will be invoked. We can use this method to populate required valued from other sources like databases or api.

Update

Update section will include all methods that are called whenever component update its view due to change of state of the component. Sequence of execution of lifecycle method is as

  1. render() : Whenever their is update in state of component then react reload its component by calling render() again.
  2. componentDidMount() : This is invoked after the render() invocation is successfully completed.

Unmount

This section we have grouped all react lifecycle method that are invoked when component is distroyed i.e component is removed from the view.

Methods in Unmount section can help in clearing resources occupied by that component. Component may clear or release its inmemory storage or cache while distroying or un-mounting itself.

Here we have

componentWillUnmount() : componentDidMount() will be called just before unmounting of the react component.

Here is the Below code snippet that will describe all component lifecycle method in action.

Also, you can get complete code from my git repo.

import React, { Component } from "react";

class Counter extends Component {
  styles = {
    fontWeight: 20,
    fontSize: 20,
  };
  constructor(props) {
    super(props);
    console.log(
      "App Construtor invoked for counter",
      this.props.counterProps.key
    );
  }
  counter = this.props.counterProps;

  render() {
    console.log("App Render invoked for counter", this.props.counterProps.key);
    return (
      <React.Fragment>
        <span style={this.styles} className={this.getBadgeClasses()}>
          {this.counter.value}
        </span>
        <button
          style={this.styles}
          className="btn btn-primary"
          onClick={() => this.props.onIncrement(this.counter)}
        >
          Increment
        </button>
        <button
          style={this.styles}
          className="btn btn-danger m-2"
          onClick={() => this.props.onDelete(this.counter.key)}
        >
          Delete
        </button>
      </React.Fragment>
    );
  }
  componentDidMount() {
    console.log(
      "App ComponentDidMoun invoked for counter",
      this.props.counterProps.key
    );
  }
  componentDidUpdate() {
    console.log(
      "App ComponentDidUpdate invoked for counter",
      this.props.counterProps.key
    );
  }
  componentWillUnmount() {
    console.log(
      "App componentWillUnmount invoked for counter",
      this.props.counterProps.key
    );
  }
  getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.counter.value === 0 ? "primary" : "warning";
    return classes;
  }
}

export default Counter;

When you run the above code you will see some thing like this.

Screent shot of component lifecycle in react

In the above image each row of button’s denote the one counter Component. And as they are created (means mounted) all logs are logged as below.

Here is the Console Output

	App Construtor invoked for counter 1
	Render invoked for counter 1
	Construtor invoked for counter 2
	Render invoked for counter 2
	Construtor invoked for counter 3
	Render invoked for counter 3
	Construtor invoked for counter 4
	Render invoked for counter 4
	App ComponentDidMoun invoked for counter 1
	App ComponentDidMoun invoked for counter 2
	App ComponentDidMoun invoked for counter 3
	App ComponentDidMoun invoked for counter 4

Now, When we create on Increment button for counter-1 (i.e Update)the log is as

	handleIncrement called
        App ComponentDidUpdate invoked for counter 1

Now When we delete one component I.e unmount

	handleDelete called
        App componentWillUnmount invoked for counter 4

Conclusion

In this post we discussed about React js component as reusable element that can be used again and again based on our need through out the react js app. They can be created mainly in two ways as a class or as a function

React component created as a class is called Class Component and the react component that is created using function paradigm is called functional or stateless component.

Class component has one required method called render() which is responsible to render component’s view to ui. This render() returns JSX. Each class component maintains its state and constructor is used for initializing values from props to state.

Functional Component or Stateless component does not maintain their state but local state can be assigned to functional component using useState().

Each class component can use react’s life cycle methods but function component can not use those methods. Lifecycle methods are grouped into mount, update and unmount group. The sequence of execution of each group is as follows.

MountUpdateUnmount
1. constructor()
2. render()
3.constructorDidMount()
1. render()
2.constructorDidUpdate()
1. componentWillUnmount()

Thanks, Note

Thanks for spending you valuable time on this post hope this post was use full to you and you learned something new today. If you like our post please share our post.

Durgesh Kumar

He is the Founder of TechiJournal.com. And have 4+ years of experience as full-stack Java developer. He worked with many reputed product companies and would like to share his experience and knowledge through this blog. He works very hard to provide you with quality content. But as no one is perfect, If you feel that some improvement can be made then feel free to add it in the comment section. We look forward to it.

Leave a Reply