React Training
  • React JS Library
  • Roadmap
  • Training OutLine
  • React js basics
    • Understanding React JS
    • React JS a framework?
    • Setting Up React
    • Say Hello to React
    • Everything is a Component
    • Create-react-app
  • React Building Blocks
    • JSX and Babel
    • One Way Data Flow
    • Virtual DOM
    • V of MVC
    • React Terminology
    • React Tooling
  • Day 01
    • Day 01 OutLine
    • All About JSX
    • React Tools/ npm & webpack
    • Introduction of Webpack
    • Hello world using webpack
      • Webpack Setting up with React
    • NPM Scripts | Package JSON
      • Package.json file
    • React JS Principles
      • One Way Data Flow
      • V of MVC
      • Virtual DOM
    • Create React App - Part-1
    • Create React App - Part-2
  • Day 02
    • Quick Recap
      • Quiz
    • State & Props
      • State & Props in Depth
      • State Vs Props | Compare
    • React LifeCycle Methods
      • React LifeCycle Methods for V-0.16 x
    • Constructor | Lifecycle
    • Write Flicker App | First App
  • Day 03
    • Quick Recap
    • Life Cycle Flow
      • Birth and Mounting
      • Initlization and Construction
      • Pre Mounting
      • Render Method
      • componentDidMount
    • Type of React Components
      • Examples- Quick Compare
      • Class and Functional components
      • Functional Components
    • YouTube application
      • Component Design
    • All in One LifeCycle
  • Assignment
    • React App development
  • Day 04
    • Quick Recap on Lifecycle
    • Lifecycle deprecated/New Methods
      • New Lifecycle Methods
    • Lets Build App Netflix | Mock
  • Assignment
    • Github battle App | Assignment
  • Day 05
    • Quick Recap : Hooks
    • ES6 Features | Hands-on
      • ES6 Code Examples
    • Next Stop - React Router | SPA
      • Code examples | Router
      • React Router Building Blocks
      • Application using react-router-dom
  • Day 06
    • Router V4 | Quick Recap
    • ES2015 | 16 Quick Recap
    • LifeCycle Methods -Part-1
    • LifeCycle Methods -Part-2
  • Day 07
    • Quick Recap | New Lifecycle
    • Quick Recap | React Routing
    • Context API | React JS
      • component with context APIs
      • Context API | examples
    • App using Hooks/Context APIs
  • Assignment
    • Assignments
  • State Management Day-08
    • Quick Recap
    • Managing React State
      • What is Redux
      • Understanding Redux
      • Hello World "Redux"
  • React Redux Day - 09
    • Redux State Manager
    • Redux Redux Development
    • Simple Application | Redux
  • Redux Live Application Day -10
    • Redux with existing Application
      • Redux with React App
      • Lets Build More Apps
      • Should I use Redux from Dan
    • Quick Look at JS in React
    • Learn By Reading
  • miscellaneous Items - Day 11
    • Hooks useReducer
    • Hooks useContext
    • Hooks useRef
    • Hooks useEffect
    • Hooks useState
    • Lazy Loading and code splitting
    • Styling React Component
  • React Next Step - Day 12
    • Topics
    • Jest and Enjyme Testing
    • Examples: Testing
  • React Native
    • What is React Native
    • Setting up Environment
      • Linux Systems
    • React Native Hello World App
    • React Native Architecture
    • React Native Vs Native
    • Expo Cli or React Native CLI
  • React Native core Fundamental
    • React Native "Hello World"
    • Course OutLine
    • Getting started with Expo App
    • Layout with Flexbox
    • Working with Styles and Events
    • Manging Component State and Props
    • Build Simple Task List Application
  • What to Debug & How to Debug
    • Debug React Native Application
Powered by GitBook
On this page

Was this helpful?

  1. Day 02

Constructor | Lifecycle

lets see how to initialize state of a component using constructor

In React realm mounting refers to the loading of components on the DOM. This phase contains a set of methods which get invoked when the component is getting initialized, and loaded on to the DOM.

The methods which get called are as follows:

  • constructor This is the first method that gets called whenever a component is created. The constructor is called only once in the whole lifecycle of a component. It’s used to set up the initial values of variables and component state.

class ContraMusicPlayer extends React.Component
constructor(props) {
  super(props);
  this.state = {
    volume: 70,
    status: 'pause'
  }
}

Usage: Setup the initial state of the component.

If we render the above component as <ContraMusicPlayer/> it will by default render with volume level at 70 and it will be in the paused state.

In React’s realm the constructor is the only place where this.state should be used. Every other method should update the state using this.setState()

One of the best use of constructor is to define the initial state of the component, which is very useful for any react application. We can also bind any event that occurs in our component in the constructor like the following.

constructor(props){
    super(props);
    this.state = {} // state object 
    this.handleEvent = this.handleEvent.bind(this);
 }

In above’s example, the event will fire after the user has clicked the button or keyup, blur or any other event and then we need to set up the context to its parent and not the child context, so we are binding this to parent. Let me take one example to simplify this explanation.

Example

// App.js

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
  }
  handleEvent(){
    console.log(this.props);
  }
  render() {
    return (
      <div className="App">
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
    );
  }
}

export default App;

Now, if you run this and see in the console, then it says like this. Uncaught TypeError: Cannot read property 'props' of undefined

That means it can not find this as a global pointer or keyword or object to the component, it finds as that function property this, not a component property.

So, we need a solution to that. Make one new file, called app1.jsx in the src folder and put the code like this.

import React, { Component } from 'react';

class App1 extends Component {
  constructor(props){
    super(props);
    this.handleEvent = this.handleEvent.bind(this);
  }
  handleEvent(){
    console.log(this.props);
  }
  render() {
    return (
      <div className="App">
        <button onClick={this.handleEvent}>Please Click</button>
      </div>
    );
  }
}

export default App1;

Now, include this file in the main.js.

// main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/app.jsx';
import App1 from './app/app1.jsx';

ReactDOM.render(<App />, document.getElementById('App'));

And in above code, just replace the following line.

ReactDOM.render(<App />, document.getElementById('App'));

with this line

ReactDOM.render(<App1 />, document.getElementById('App1'));

Now, again run, you can see an empty object in the console. So now, this is pointing to the global context of the React component.

Following example will not working because, I have not use app1.jsx. You can use app1.jsx and modify the main.js as I have mentioned earlier.

Then see in the console, you can find empty object, if you got any error, then please check again the code, you might not have imported app1.jsx in the main.js.

So, we can achieve two purposes with the constructor function.

  1. Set the initial state of the component

  2. Point the global context of this keyword.

Arrow Functions

If you are using arrow functions then, you do not need to bind any event to this. In that scenario, this scope is global and not limited to any calling function. So If you are using ES6 syntax, then it is best practice to use Arrow Function

import React, { Component } from 'react';

class App2 extends Component {
 constructor(props){
   super(props);
 }
 handleEvent = () => {
   console.log(this.props);
 }
 render() {
   return (
     <div className="App">
       <button onClick={this.handleEvent}>Please Click</button>
     </div>
   );
 }
}

export default App2;
PreviousReact LifeCycle Methods for V-0.16 xNextWrite Flicker App | First App

Last updated 5 years ago

Was this helpful?