React Components

What is React Component ?

Component are the fundamental unit of react app.

Each component corresponds to an element in DOM.

The component is responsible for rendering the contetn of that and element and handling any events that occur with in it.

Components can nested in another components i.e nothing but Nested DOM's.




Component Syntax:




So component is function as above and returns UI element by taking the inputs PROPS i.e model



import ReactDOM from 'react-dom';// to use JSX


import React from 'react'// to get access to render functions


function Hello(props){


  return <h1>Hello at {props.now}</h1>


}


ReactDom.Render(<Hello now={new Date().tooString()  }/>,


document.getElementById('root')


)



Props in Components:






So here Sum is a component which takes props as arguments and props contains the key-value pairs which are  passed from the JSX representation of Sum component.

Props is accessed in function using below synatx:

props.variable_name i.e props.a as above.

Class Components:

We can represent components using Classes also. 

See below:




So here Sum which is using function component is converted to  Class component and props are passed similarly from JSX and those props are automatically available in Class with keyword props and can be accessed as above.

NOTE:
Class should extend React.Component and should have only one render()  function.
Also function and Class components names should start with Capital letter


Class Components allow you to override lifecycle Methods if you need to perform operations at particular times in a components life cycle such as 


  • when it has been created  or 
  • immediately after it has been inserted into the DOM.




NOTE:


Methods with will immediately before the verb are called immediately prior to that verb happening. 

For example:

componentWillMount is called immediately prior to the component mounting. 


Methods with did immediately prior to the verb are called immediately after that verb happens. 

For example: 

componentDidMount.


When to Use?

            Component lifecycle methods are useful when you are implementing a React component to wrap an imperative API. 

For example: 

You may be creating a React component for a jQuery plugin. You would use the component lifecycle methods to initialize the jQuery plugin and possibly to remove it when it is no longer required. 

Above picture shows some of the lifecycle hooks that are available during the mounting and updating phases of a component's lifecycle. 


State:

In addition to props React components have another way of holding data called State.

Props are values passed in by a component's parent. Its state is local, mutable data that can be created and modified within the component. Having local data that can change within a component increases complexity and limits the composability of the component. As such, you should avoid using state when possible which is nearly always.

For Example:

See below React component that counted the number of times it has been clicked. If we wanted that component to be self-contained we could move the click count into the component state. 

To use State we have to use a class component. 

In the class constructor we initialize the component state to a sensible default. In this case an object with a clicks property with the value zero. 

When we display the click count we read the value from the state property not from props because clicks is an internal state value, not an external props value. 




In the onClick handler we use the setState function to set the state to a new value. 

It's important to use the setState method rather than updating the state directly so that React knows that the state has changed and the component should be re-rendered. 

It's usually better to store and manage application state centrally so avoid class components and state whenever possible. 

This is the ClickCounter component implemented with local state.As in the above picture we have a constructor for the class which initializes the clicks to zero. 

When the component is rendered it outputs some text, this div has been clicked, followed by the clicks value from the local state. 

When tested it out, say each time that you click on the component the number of clicks is incremented and that's happening via the onClick handler on this div and every time there's a click event we handle that event, we call setState and we set the state to whatever the clicks value was before plus one.


setState:

The setState method merges the new state with the old state. 

All of the previous state remains unless it is overwritten. 
For example: a value in below case.

Consider a state object with properties a and b having values one and two respectively. 

Calling setState with the properties b equals three and c equals four produces a new state object.

 The property a is unchanged. The property b is overwritten by the new state and property c is newly added. 

In addition to changing the state of the component setState also causes the component to be re-rendered eventually. 

For performance reasons setState calls a batched. There is no guarantee that the state change will occur immediately.




Props Validation:

As seen in Props in Components section , we can pass string and number and can produce below result but our intent is to add two numbers.


function Sum(props){
 return <h1>{props.a} + {props.b} = {props.a+props.b}</h1> ;  
}

ReactDOM.render(
    <Sum a={"a"} b={2}/>,document.getElementById('root')
);

Output:

a + 2 = a2


So, How do validate output ?

Answer:  we use propTypes and it is defined in  separate npm package called 'prop-types'

How do we use it ?

Answer: see below i.e function_name.proptypes{
variable_name :validation
}

import React from 'react';
import './bootstrap.min.css';
import PropTypes from 'prop-types';
 
function Sum(props){
 return <h1>{props.a} + {props.b} = {props.a+props.b}</h1> ;  
}
Sum.propTypes = {
    a : PropTypes.number.isRequired,
    b : PropTypes.number.isRequired
}

ReactDOM.render(
    <Sum a={"a"} b={2}/>,document.getElementById('root')
);


If you run above code you will see below error in console

Error:

index.js:1 Warning: Failed prop type: Invalid prop `a` of type `string` supplied to `Sum`, expected `number`.
    in Sum (at src/index.js:10)
console.<computed> @ index.js:1

So to allow static type checking we use PropTypes which is a basic type checker which has been patched onto React.

Also we use Flow is a static analysis tool which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time.

Post a Comment

0 Comments