React: Demystifying Component, Props, and State

React: Demystifying Component, Props, and State


******************* 1.0) Part-1: Component - Start *************************

What is React Component?

Background:

In real-life scenario, when project become larger and larger, its very difficult to put all the millions line of the code into one large file and maintain it smoothly. In order to overcome this complexity, Component is born out.

1.1) A component is an independent, reusable code block, which divides the UI into smaller pieces.

1.2) Each component has its own JS and CSS code. So, its reusable, easier to read, write and test.

1.3) React has two types of components: Functional (Stateless) and Class (Stateful).

1.4) Functional (Stateless) Components

A functional component is basically a JavaScript (or ES6) function which returns a React element.

- is a JavaScript / ES6 function,

- must return a React element,

- take props as parameter if required.

function Greet( props ) {

  return <h1> Hello, {props.username}</h1>;

}


or as an ES6 arrow function:

const Greet = ( props ) =>

{ return <h1> Hello, {props.username}</h1>;}



1.5) Class (Stateful) Components

Basically, Class components are ES6 classes. Its including constructors, life-cycle methods, render( ) function and state (data) management. Its more complex than the functional component.

So, a React class component:

- is an ES6 class, will be a component once it ‘extends’ React component,

- can accept props (in the constructor) if required,

- can maintain its own data with state,

- must have a render( ) method which returns a React element (JSX), or null

1.6) Example

// FirstChildjs


import React, { Component) from ''react';

const FirstChild =(props) =>{ 

    return( <p> Its the child component !!! </p>)

};

export default FirstChild;pot default FirstChild;

**************************************************************************

//ParentComponent.js

import React, { Component) from ''react';

import FirstChild from "./FirstChild";

class ParentComponent extends component{

render(){

     return(

              <h1> 

                    Its parent component.

                    <FirstChild/> 

             </h1>

       );

}}

export default ParentComponent;

**************************************************************************

Calling the ParentComponent from the root(App function. So, we can see it in the webpage.

//App.js

import React from 'react';
import './App.css';
import ParentComponent from './ParentComponent';


const App = () =>{
    return (
        <div className="App">
            <ParentComponent/>
        </div>
    );
}


******************* 1.0) Part-1: Component - End *************************


******************* 2.0) Part-2: Props - Start *************************

What is Props?

2.1) 'Props' is a special keyword in React, which stands for properties.

2.2) 'Props' is used for passing data from one component to another.

2.3) 'Props' pass data in uni-direction (Parent-to-Child).

2.4) 'Props' data is immutable i.e, read-only i.e, data coming from the parent should not be changed by child components.

2.5) 'Props' are being passed to components like function arguments.

'Props' are arguments passed into React components. — w3schools.com

2.6) Example

//MyParentComponent.js
//=======================

import React, { Component} from ''react';



class MyParentComponent extends Component {  

  render() {

    return (

      <h1> Its Parent component.

       <ChildComponent text={"Its 1st child"} />

        <ChildComponent text={"Its 2nd child"} />

        <ChildComponent text={"Its 3rd child"} />  

      </h1> );
}}

export default MyParentComponent;


// MyChildComponent.js
//======================

import React, { Component) from ''react';



const ChildComponent = (props) => {  

  return <p>{props.text}</p>; 

};



******************* 2.0) Part-2: Props - End *************************


******************* 3.0) Part-3: State - Start *************************

Background:

In the real-life scenario, child component may need to change/mutate the data. But, we know that 'Props' are only used for passing immutable data to child component.

To handle this situation React provide another feature which is know as 'State'.

What is State?

3.1) 'State' is a special object that holds dynamic data, which can change on the fly.

3.2) 'State' is initialised inside its component's constructor method.

3.3) 'State' is private, so only belong to component which defined it. It cannot be accessed from outside. But, 'State' can be passed to child components via 'Props'.

3.4) A change in the 'State' is made only through the special method setState(). It shouldn't modified directly.

Like: Below is not recommended:

this.state.username = "New UserName".

3.5) Due to performance reason, 'State' shouldn't overly - used.

3.6) Example

a) Creating State

// MySBP.js
//==============================

import React, { Component) from ''react';

class MySBP extends React.Component {

 constructor() {

  this.state = {

   id: 1,

   username: "SBP"

  };
  }

  

 render() {

  return (

   <div>

    <p>{this.state.id}</p>

    <p>{this.state.username}</p>

   </div>

  );
 }


}

export default MySBP;


b) Modifying State by using setState( )

As we know that when a change in the 'State' happens, React takes this information and updates the UI.

this.setState({

username: "New UserName"

});


c) Why we should only use setState() to modify 'State'?

Because its the only way to notify React for data changes. Otherwise React wont't be notified and won't be able to update the UI.

******************* 3.0) Part-3: State - End *************************

要查看或添加评论,请登录

Arun Dhwaj的更多文章

  • Data Flow Diagram (DFD): Brief Tutorial

    Data Flow Diagram (DFD): Brief Tutorial

    1) How to create it Step1: Start with definition and purpose. Step2: Explain components with symbols.

    1 条评论
  • Translation of Work to ROI

    Translation of Work to ROI

    Why Translate Your Work to ROI ( Return On Investment) ? 1) It will make easy for you to show your stakeholders, about…

  • Sr. Architect/ Solution Architect Responsibility

    Sr. Architect/ Solution Architect Responsibility

    I) A brief dive of Responsibility 1) Understand the System’s Requirements, 2) Understand the Non-Functional…

  • 7 Tips for Optimising System Performance

    7 Tips for Optimising System Performance

    Step-1:Measure most of the things as much as you can. Step-2: Prioritise based on outcome vs intake/ Cost ( Money/…

  • Great Leader creates DNA/Culture

    Great Leader creates DNA/Culture

    They took the following steps to creates: 1) Routine The purpose of Routine is to creates The Sense of Community and…

  • Leadership: Remotely Leading the Team

    Leadership: Remotely Leading the Team

    1) Be Output Oriented Instead of inputs, be output oriented. Explain the team, they would like to see these…

  • Be on the TOP of the WORLD

    Be on the TOP of the WORLD

    1) Be a Constant Learner Make a habit of learning, learning and learning. There is no alternative to a constant…

  • Troubleshooting/ Debugging: Kubernetes Pods

    Troubleshooting/ Debugging: Kubernetes Pods

    1) Background 1.1) Throughout we will use kubectl command-line utility to interact with K8S.

  • Best Practice: Versioning REST API

    Best Practice: Versioning REST API

    1) When we should do the Versioning of API Versioning (REST) API is often a last priority during development process…

  • Java: Stopping Serialization and Deserialization

    Java: Stopping Serialization and Deserialization

    There are scenario/ situation where we want to avoid our class to be serialized or deserialized. Like: our class is a…

社区洞察

其他会员也浏览了