Author: saqibkhan

  • Events

    An event is an action that could be triggered as a result of the user action or system generated event. For example, a mouse click, loading of a web page, pressing a key, window resizes, and other interactions are called events.

    React has its own event handling system which is very similar to handling events on DOM elements. The react event handling system is known as Synthetic Events. The synthetic event is a cross-browser wrapper of the browser’s native event.

    React Events

    Handling events with react have some syntactic differences from handling events on DOM. These are:

    1. React events are named as camelCase instead of lowercase.
    2. With JSX, a function is passed as the event handler instead of a string. For example:

    Event declaration in plain HTML:

    <button onclick="showMessage()">  
    
           Hello JavaTpoint  
    
    </button> 

    Event declaration in React:

    <button onClick={showMessage}>  
    
          Hello JavaTpoint  
    
    </button>

    3. In react, we cannot return false to prevent the default behavior. We must call preventDefault event explicitly to prevent the default behavior. For example:

    In plain HTML, to prevent the default link behavior of opening a new page, we can write:

    <a href="#" onclick="console.log('You had clicked a Link.'); return false">  
    
        Click_Me  
    
    </a> 

    In React, we can write it as:

    function ActionLink() {  
    
        function handleClick(e) {  
    
            e.preventDefault();  
    
            console.log('You had clicked a Link.');  
    
        }  
    
        return (  
    
            <a href="#" onClick={handleClick}>  
    
                  Click_Me  
    
            </a>  
    
        );  
    
    } 

    In the above example, e is a Synthetic Event which defines according to the W3C spec.

    Now let us see how to use Event in React.

    Example

    In the below example, we have used only one component and adding an onChange event. This event will trigger the changeText function, which returns the company name.

    import React, { Component } from 'react';  
    
    class App extends React.Component {  
    
        constructor(props) {  
    
            super(props);  
    
            this.state = {  
    
                companyName: ''  
    
            };  
    
        }  
    
        changeText(event) {  
    
            this.setState({  
    
                companyName: event.target.value  
    
            });  
    
        }  
    
        render() {  
    
            return (  
    
                <div>  
    
                    <h2>Simple Event Example</h2>  
    
                    <label htmlFor="name">Enter company name: </label>  
    
                    <input type="text" id="companyName" onChange={this.changeText.bind(this)}/>  
    
                    <h4>You entered: { this.state.companyName }</h4>  
    
                </div>  
    
            );  
    
        }  
    
    }  
    
    export default App;  

    Output

    When you execute the above code, you will get the following output.

    React Events

    After entering the name in the textbox, you will get the output as like below screen.

    React Events
  • Controlled Vs. Uncontrolled Component

    Controlled Component

    A controlled component is bound to a value, and its changes will be handled in code by using event-based callbacks. Here, the input form element is handled by the react itself rather than the DOM. In this, the mutable state is kept in the state property and will be updated only with setState() method.

    Controlled components have functions that govern the data passing into them on every onChange event occurs. This data is then saved to state and updated with setState() method. It makes component have better control over the form elements and data.

    Uncontrolled Component

    It is similar to the traditional HTML form inputs. Here, the form data is handled by the DOM itself. It maintains their own state and will be updated when the input value changes. To write an uncontrolled component, there is no need to write an event handler for every state update, and you can use a ref to access the value of the form from the DOM.

    Difference table between controlled and uncontrolled component

    SNControlledUncontrolled
    1.It does not maintain its internal state.It maintains its internal states.
    2.Here, data is controlled by the parent component.Here, data is controlled by the DOM itself.
    3.It accepts its current value as a prop.It uses a ref for their current values.
    4.It allows validation control.It does not allow validation control.
    5.It has better control over the form elements and data.It has limited control over the form elements and data.
  • Forms

    Forms are an integral part of any modern web application. It allows the users to interact with the application as well as gather information from the users. Forms can perform many tasks that depend on the nature of your business requirements and logic such as authentication of the user, adding user, searching, filtering, booking, ordering, etc. A form can contain text fields, buttons, checkbox, radio button, etc.

    Creating Form

    React offers a stateful, reactive approach to build a form. The component rather than the DOM usually handles the React form. In React, the form is usually implemented by using controlled components.

    There are mainly two types of form input in React.

    1. Uncontrolled component
    2. Controlled component

    Uncontrolled component

    The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM.

    Example

    In this example, the code accepts a field username and company name in an uncontrolled component.

    import React, { Component } from 'react';  
    
    class App extends React.Component {  
    
      constructor(props) {  
    
          super(props);  
    
          this.updateSubmit = this.updateSubmit.bind(this);  
    
          this.input = React.createRef();  
    
      }  
    
      updateSubmit(event) {  
    
          alert('You have entered the UserName and CompanyName successfully.');  
    
          event.preventDefault();  
    
      }  
    
      render() {  
    
        return (  
    
          <form onSubmit={this.updateSubmit}>  
    
            <h1>Uncontrolled Form Example</h1>  
    
            <label>Name:  
    
                <input type="text" ref={this.input} />  
    
            </label>  
    
            <label>  
    
                CompanyName:  
    
                <input type="text" ref={this.input} />  
    
            </label>  
    
            <input type="submit" value="Submit" />  
    
          </form>  
    
        );  
    
      }  
    
    }  
    
    export default App;  

      Output

      When you execute the above code, you will see the following screen.

      React Forms

      After filling the data in the field, you get the message that can be seen in the below screen.

      React Forms

      Controlled Component

      In HTML, form elements typically maintain their own state and update it according to the user input. In the controlled component, the input form element is handled by the component rather than the DOM. Here, the mutable state is kept in the state property and will be updated only with setState() method.

      Controlled components have functions that govern the data passing into them on every onChange event, rather than grabbing the data only once, e.g., when you click a submit button. This data is then saved to state and updated with setState() method. This makes component have better control over the form elements and data.

      A controlled component takes its current value through props and notifies the changes through callbacks like an onChange event. A parent component “controls” this changes by handling the callback and managing its own state and then passing the new values as props to the controlled component. It is also called as a “dumb component.”

      Example

      import React, { Component } from 'react';  
      
      class App extends React.Component {  
      
        constructor(props) {  
      
            super(props);  
      
            this.state = {value: ''};  
      
            this.handleChange = this.handleChange.bind(this);  
      
            this.handleSubmit = this.handleSubmit.bind(this);  
      
        }  
      
        handleChange(event) {  
      
            this.setState({value: event.target.value});  
      
        }  
      
        handleSubmit(event) {  
      
            alert('You have submitted the input successfully: ' + this.state.value);  
      
            event.preventDefault();  
      
        }  
      
        render() {  
      
            return (  
      
                <form onSubmit={this.handleSubmit}>  
      
                  <h1>Controlled Form Example</h1>  
      
                  <label>  
      
                      Name:  
      
                      <input type="text" value={this.state.value} onChange={this.handleChange} />  
      
                  </label>  
      
                  <input type="submit" value="Submit" />  
      
               </form>  
      
            );  
      
        }  
      
      }  
      
      export default App;

      Output

      When you execute the above code, you will see the following screen.

      React Forms

      After filling the data in the field, you get the message that can be seen in the below screen.

      React Forms

      Handling Multiple Inputs in Controlled Component

      If you want to handle multiple controlled input elements, add a name attribute to each element, and then the handler function decided what to do based on the value of event.target.name.

      Example

      import React, { Component } from 'react';  
      
      class App extends React.Component {  
      
          constructor(props) {  
      
              super(props);  
      
              this.state = {  
      
                  personGoing: true,  
      
                  numberOfPersons: 5  
      
              };  
      
              this.handleInputChange = this.handleInputChange.bind(this);  
      
         }  
      
         handleInputChange(event) {  
      
             const target = event.target;  
      
             const value = target.type === 'checkbox' ? target.checked : target.value;  
      
             const name = target.name;  
      
             this.setState({  
      
                 [name]: value  
      
             });  
      
        }  
      
        render() {  
      
            return (  
      
                <form>  
      
                    <h1>Multiple Input Controlled Form Example</h1>  
      
                    <label>  
      
                        Is Person going:  
      
                        <input  
      
                          name="personGoing"  
      
                          type="checkbox"  
      
                          checked={this.state.personGoing}  
      
                          onChange={this.handleInputChange} />  
      
                   </label>  
      
                   <br />  
      
                   <label>  
      
                       Number of persons:  
      
                       <input  
      
                       name="numberOfPersons"  
      
                       type="number"  
      
                       value={this.state.numberOfPersons}  
      
                       onChange={this.handleInputChange} />  
      
                   </label>  
      
               </form>  
      
           );  
      
        }  
      
      }  
      
      export default App;  

        Output

        React Forms
      1. Component Life-Cycle

        In ReactJS, every component creation process involves various lifecycle methods. These lifecycle methods are termed as component’s lifecycle. These lifecycle methods are not very complicated and called at various points during a component’s life. The lifecycle of the component is divided into four phases. They are:

        1. Initial Phase
        2. Mounting Phase
        3. Updating Phase
        4. Unmounting Phase

        Each phase contains some lifecycle methods that are specific to the particular phase. Let us discuss each of these phases one by one.

        1. Initial Phase

        It is the birth phase of the lifecycle of a ReactJS component. Here, the component starts its journey on a way to the DOM. In this phase, a component contains the default Props and initial State. These default properties are done in the constructor of a component. The initial phase only occurs once and consists of the following methods.

        • getDefaultProps()
          It is used to specify the default value of this.props. It is invoked before the creation of the component or any props from the parent is passed into it.
        • getInitialState()
          It is used to specify the default value of this.state. It is invoked before the creation of the component.

        2. Mounting Phase

        In this phase, the instance of a component is created and inserted into the DOM. It consists of the following methods.

        • componentWillMount()
          This is invoked immediately before a component gets rendered into the DOM. In the case, when you call setState() inside this method, the component will not re-render.
        • componentDidMount()
          This is invoked immediately after a component gets rendered and placed on the DOM. Now, you can do any DOM querying operations.
        • render()
          This method is defined in each and every component. It is responsible for returning a single root HTML node element. If you don’t want to render anything, you can return a null or false value.

        3. Updating Phase

        It is the next phase of the lifecycle of a react component. Here, we get new Props and change State. This phase also allows to handle user interaction and provide communication with the components hierarchy. The main aim of this phase is to ensure that the component is displaying the latest version of itself. Unlike the Birth or Death phase, this phase repeats again and again. This phase consists of the following methods.

        • componentWillRecieveProps()
          It is invoked when a component receives new props. If you want to update the state in response to prop changes, you should compare this.props and nextProps to perform state transition by using this.setState() method.
        • shouldComponentUpdate()
          It is invoked when a component decides any changes/updation to the DOM. It allows you to control the component’s behavior of updating itself. If this method returns true, the component will update. Otherwise, the component will skip the updating.
        • componentWillUpdate()
          It is invoked just before the component updating occurs. Here, you can’t change the component state by invoking this.setState() method. It will not be called, if shouldComponentUpdate() returns false.
        • render()
          It is invoked to examine this.props and this.state and return one of the following types: React elements, Arrays and fragments, Booleans or null, String and Number. If shouldComponentUpdate() returns false, the code inside render() will be invoked again to ensure that the component displays itself properly.
        • componentDidUpdate()
          It is invoked immediately after the component updating occurs. In this method, you can put any code inside this which you want to execute once the updating occurs. This method is not invoked for the initial render.

        4. Unmounting Phase

        It is the final phase of the react component lifecycle. It is called when a component instance is destroyed and unmounted from the DOM. This phase contains only one method and is given below.

        • componentWillUnmount()
          This method is invoked immediately before a component is destroyed and unmounted permanently. It performs any necessary cleanup related task such as invalidating timers, event listener, canceling network requests, or cleaning up DOM elements. If a component instance is unmounted, you cannot mount it again.

        Example

        import React, { Component } from 'react';  
        
          
        
        class App extends React.Component {  
        
           constructor(props) {  
        
              super(props);  
        
              this.state = {hello: "JavaTpoint"};  
        
              this.changeState = this.changeState.bind(this)  
        
           }    
        
           render() {  
        
              return (  
        
                 <div>  
        
                     <h1>ReactJS component's Lifecycle</h1>  
        
                     <h3>Hello {this.state.hello}</h3>  
        
                     <button onClick = {this.changeState}>Click Here!</button>          
        
                 </div>  
        
              );  
        
           }  
        
           componentWillMount() {  
        
              console.log('Component Will MOUNT!')  
        
           }  
        
           componentDidMount() {  
        
              console.log('Component Did MOUNT!')  
        
           }  
        
           changeState(){  
        
              this.setState({hello:"All!!- Its a great reactjs tutorial."});  
        
           }  
        
           componentWillReceiveProps(newProps) {      
        
              console.log('Component Will Recieve Props!')  
        
           }  
        
           shouldComponentUpdate(newProps, newState) {  
        
              return true;  
        
           }  
        
           componentWillUpdate(nextProps, nextState) {  
        
              console.log('Component Will UPDATE!');  
        
           }  
        
           componentDidUpdate(prevProps, prevState) {  
        
              console.log('Component Did UPDATE!')  
        
           }  
        
           componentWillUnmount() {  
        
              console.log('Component Will UNMOUNT!')  
        
           }  
        
        }  
        
        export default App;  

          Output:

          React Component Life-Cycle

          When you click on the Click Here Button, you get the updated result which is shown in the below screen.

          React Component Life-Cycle
        1. Component API

          ReactJS component is a top-level API. It makes the code completely individual and reusable in the application. It includes various methods for:

          • Creating elements
          • Transforming elements
          • Fragments

          Here, we are going to explain the three most important methods available in the React component API.

          1. setState()
          2. forceUpdate()
          3. findDOMNode()

          setState()

          This method is used to update the state of the component. This method does not always replace the state immediately. Instead, it only adds changes to the original state. It is a primary method that is used to update the user interface(UI) in response to event handlers and server responses.

          Note: In the ES6 classes, this.method.bind(this) is used to manually bind the setState() method.

          Syntax

          this.stateState(object newState[, function callback]);  

          In the above syntax, there is an optional callback function which is executed once setState() is completed and the component is re-rendered.

          Example

          import React, { Component } from 'react';  
          
          import PropTypes from 'prop-types';  
          
          class App extends React.Component {  
          
             constructor() {  
          
                super();        
          
                this.state = {  
          
                    msg: "Welcome to JavaTpoint"  
          
                };      
          
                this.updateSetState = this.updateSetState.bind(this);  
          
             }  
          
             updateSetState() {  
          
                 this.setState({  
          
                    msg:"Its a best ReactJS tutorial"  
          
                 });  
          
             }  
          
             render() {  
          
                return (  
          
                   <div>  
          
                       <h1>{this.state.msg}</h1>  
          
                       <button onClick = {this.updateSetState}>SET STATE</button>  
          
                   </div>  
          
                );  
          
             }  
          
          }  
          
          export default App;  

            Main.js

            import React from 'react';  
            
            import ReactDOM from 'react-dom';  
            
            import App from './App.js';  
            
              
            
            ReactDOM.render(<App/>, document.getElementById('app'));  

              Output:

              React Component API

              When you click on the SET STATE button, you will see the following screen with the updated message.

              React Component API

              forceUpdate()

              This method allows us to update the component manually.

              Syntax

              Component.forceUpdate(callback);  

              Example

              App.js

              import React, { Component } from 'react';  
              
              class App extends React.Component {  
              
                 constructor() {  
              
                    super();            
              
                    this.forceUpdateState = this.forceUpdateState.bind(this);  
              
                 }  
              
                 forceUpdateState() {  
              
                    this.forceUpdate();  
              
                 };  
              
                 render() {  
              
                    return (  
              
                       <div>  
              
                           <h1>Example to generate random number</h1>  
              
                           <h3>Random number: {Math.random()}</h3>  
              
                           <button onClick = {this.forceUpdateState}>ForceUpdate</button>  
              
                       </div>  
              
                    );  
              
                 }  
              
              }  
              
              export default App;  

                Output:

                React Component API

                Each time when you click on ForceUpdate button, it will generate the random number. It can be shown in the below image.

                React Component API

                findDOMNode()

                For DOM manipulation, you need to use ReactDOM.findDOMNode() method. This method allows us to find or access the underlying DOM node.

                Syntax

                ReactDOM.findDOMNode(component);  

                Example

                For DOM manipulation, first, you need to import this line: import ReactDOM from ‘react-dom‘ in your App.js file.

                App.js

                import React, { Component } from 'react';  
                
                import ReactDOM from 'react-dom';  
                
                class App extends React.Component {  
                
                   constructor() {  
                
                      super();  
                
                      this.findDomNodeHandler1 = this.findDomNodeHandler1.bind(this);  
                
                      this.findDomNodeHandler2 = this.findDomNodeHandler2.bind(this);  
                
                   };  
                
                   findDomNodeHandler1() {  
                
                       var myDiv = document.getElementById('myDivOne');  
                
                       ReactDOM.findDOMNode(myDivOne).style.color = 'red';  
                
                   }  
                
                   findDomNodeHandler2() {  
                
                       var myDiv = document.getElementById('myDivTwo');  
                
                       ReactDOM.findDOMNode(myDivTwo).style.color = 'blue';  
                
                   }  
                
                   render() {  
                
                      return (  
                
                         <div>  
                
                             <h1>ReactJS Find DOM Node Example</h1>  
                
                             <button onClick = {this.findDomNodeHandler1}>FIND_DOM_NODE1</button>  
                
                             <button onClick = {this.findDomNodeHandler2}>FIND_DOM_NODE2</button>  
                
                             <h3 id = "myDivOne">JTP-NODE1</h3>  
                
                             <h3 id = "myDivTwo">JTP-NODE2</h3>  
                
                         </div>  
                
                      );  
                
                   }  
                
                }  
                
                export default App; 

                  Output:

                  React Component API

                  Once you click on the button, the color of the node gets changed. It can be shown in the below screen.

                  React Component API
                1. What is Constructor?

                  The constructor is a method used to initialize an object’s state in a class. It automatically called during the creation of an object in a class.

                  The concept of a constructor is the same in React. The constructor in a React component is called before the component is mounted. When you implement the constructor for a React component, you need to call super(props) method before any other statement. If you do not call super(props) method, this.props will be undefined in the constructor and can lead to bugs.

                  Syntax

                  Constructor(props){  
                  
                       super(props);  
                  
                  } 

                    In React, constructors are mainly used for two purposes:

                    1. It used for initializing the local state of the component by assigning an object to this.state.
                    2. It used for binding event handler methods that occur in your component.

                    Note: If you neither initialize state nor bind methods for your React component, there is no need to implement a constructor for React component.

                    You cannot call setState() method directly in the constructor(). If the component needs to use local state, you need directly to use ‘this.state‘ to assign the initial state in the constructor. The constructor only uses this.state to assign initial state, and all other methods need to use set.state() method.

                    Example

                    The concept of the constructor can understand from the below example.

                    App.js

                    import React, { Component } from 'react';  
                    
                      
                    
                    class App extends Component {  
                    
                      constructor(props){  
                    
                        super(props);  
                    
                        this.state = {  
                    
                             data: 'www.javatpoint.com'  
                    
                          }  
                    
                        this.handleEvent = this.handleEvent.bind(this);  
                    
                      }  
                    
                      handleEvent(){  
                    
                        console.log(this.props);  
                    
                      }  
                    
                      render() {  
                    
                        return (  
                    
                          <div className="App">  
                    
                        <h2>React Constructor Example</h2>  
                    
                        <input type ="text" value={this.state.data} />  
                    
                            <button onClick={this.handleEvent}>Please Click</button>  
                    
                          </div>  
                    
                        );  
                    
                      }  
                    
                    }  
                    
                    export default App;  

                      Main.js

                      import React from 'react';  
                      
                      import ReactDOM from 'react-dom';  
                      
                      import App from './App.js';  
                      
                        
                      
                      ReactDOM.render(<App />, document.getElementById('app')); 

                        Output

                        When you execute the above code, you get the following output.

                        React Constructor

                        The most common question related to the constructor are:

                        1. Is it necessary to have a constructor in every component?

                        No, it is not necessary to have a constructor in every component. If the component is not complex, it simply returns a node.

                        class App extends Component {  
                        
                            render () {  
                        
                                return (  
                        
                                    <p> Name: { this.props.name }</p>  
                        
                                );  
                        
                            }  
                        
                        }  

                          2. Is it necessary to call super() inside a constructor?

                          Yes, it is necessary to call super() inside a constructor. If you need to set a property or access ‘this’ inside the constructor in your component, you need to call super().

                          class App extends Component {  
                          
                              constructor(props){  
                          
                                  this.fName = "Jhon"; // 'this' is not allowed before super()  
                          
                              }  
                          
                              render () {  
                          
                                  return (  
                          
                                      <p> Name: { this.props.name }</p>  
                          
                                  );  
                          
                              }  
                          
                          } 

                            When you run the above code, you get an error saying ‘this’ is not allowed before super(). So if you need to access the props inside the constructor, you need to call super(props).

                            Arrow Functions

                            The Arrow function is the new feature of the ES6 standard. If you need to use arrow functions, it is not necessary to bind any event to ‘this.’ Here, the scope of ‘this’ is global and not limited to any calling function. So If you are using Arrow Function, there is no need to bind ‘this’ inside the constructor.

                            import React, { Component } from 'react';  
                            
                              
                            
                            class App extends Component {  
                            
                              constructor(props){  
                            
                                super(props);  
                            
                                this.state = {  
                            
                                     data: 'www.javatpoint.com'  
                            
                                  }  
                            
                              }  
                            
                              handleEvent = () => {  
                            
                                console.log(this.props);  
                            
                              }  
                            
                              render() {  
                            
                                return (  
                            
                                  <div className="App">  
                            
                                <h2>React Constructor Example</h2>  
                            
                                <input type ="text" value={this.state.data} />  
                            
                                    <button onClick={this.handleEvent}>Please Click</button>  
                            
                                  </div>  
                            
                                );  
                            
                              }  
                            
                            }  
                            
                            export default App;

                            We can use a constructor in the following ways:

                            1) The constructor is used to initialize state.

                            class App extends Component {  
                            
                              constructor(props){  
                            
                                    // here, it is setting initial value for 'inputTextValue'  
                            
                                    this.state = {  
                            
                                        inputTextValue: 'initial value',  
                            
                                    };  
                            
                              }  
                            
                            }  

                              2) Using ‘this’ inside constructor

                              class App extends Component {  
                              
                                  constructor(props) {  
                              
                                      // when you use 'this' in constructor, super() needs to be called first  
                              
                                      super();  
                              
                                      // it means, when you want to use 'this.props' in constructor, call it as below  
                              
                                      super(props);  
                              
                                  }  
                              
                              } 

                                3) Initializing third-party libraries

                                class App extends Component {  
                                
                                    constructor(props) {  
                                
                                  
                                
                                        this.myBook = new MyBookLibrary();  
                                
                                  
                                
                                        //Here, you can access props without using 'this'  
                                
                                        this.Book2 = new MyBookLibrary(props.environment);  
                                
                                    }  
                                
                                } 

                                  4) Binding some context(this) when you need a class method to be passed in props to children.

                                  class App extends Component {  
                                  
                                      constructor(props) {  
                                  
                                    
                                  
                                          // when you need to 'bind' context to a function  
                                  
                                          this.handleFunction = this.handleFunction.bind(this);  
                                  
                                      }  
                                  
                                  }
                                1. State Vs. Props

                                  State

                                  The state is an updatable structure that is used to contain data or information about the component and can change over time. The change in state can happen as a response to user action or system event. It is the heart of the react component which determines the behavior of the component and how it will render. A state must be kept as simple as possible. It represents the component’s local state or information. It can only be accessed or modified inside the component or by the component directly.

                                  Props

                                  Props are read-only components. It is an object which stores the value of attributes of a tag and work similar to the HTML attributes. It allows passing data from one component to other components. It is similar to function arguments and can be passed to the component the same way as arguments passed in a function. Props are immutable so we cannot modify the props from inside the component.

                                  Difference between State and Props

                                  SNPropsState
                                  1.Props are read-only.State changes can be asynchronous.
                                  2.Props are immutable.State is mutable.
                                  3.Props allow you to pass data from one component to other components as an argument.State holds information about the components.
                                  4.Props can be accessed by the child component.State cannot be accessed by child components.
                                  5.Props are used to communicate between components.States can be used for rendering dynamic changes with the component.
                                  6.Stateless component can have Props.Stateless components cannot have State.
                                  7.Props make components reusable.State cannot make components reusable.
                                  8.Props are external and controlled by whatever renders the component.The State is internal and controlled by the React Component itself.

                                  The below table will guide you about the changing in props and state.

                                  SNConditionPropsState
                                  1.Can get initial value from parent Component?YesYes
                                  2.Can be changed by parent Component?YesNo
                                  3.Can set default values inside Component?YesYes
                                  4.Can change inside Component?NoYes
                                  5.Can set initial value for child Components?YesYes
                                  6.Can change in child Components?YesNo

                                  Note: The component State and Props share some common similarities. They are given in the below table.

                                  SNState and Props
                                  1.Both are plain JS object.
                                  2.Both can contain default values.
                                  3.Both are read-only when they are using by this.
                                2. Props Validation

                                  Props are an important mechanism for passing the read-only attributes to React components. The props are usually required to use correctly in the component. If it is not used correctly, the components may not behave as expected. Hence, it is required to use props validation in improving react components.

                                  Props validation is a tool that will help the developers to avoid future bugs and problems. It is a useful way to force the correct usage of your components. It makes your code more readable. React components used special property PropTypes that help you to catch bugs by validating data types of values passed through props, although it is not necessary to define components with propTypes. However, if you use propTypes with your components, it helps you to avoid unexpected bugs.

                                  Validating Props

                                  App.propTypes is used for props validation in react component. When some of the props are passed with an invalid type, you will get the warnings on JavaScript console. After specifying the validation patterns, you will set the App.defaultProps.

                                  Syntax:

                                  class App extends React.Component {  
                                  
                                            render() {}  
                                  
                                  }  
                                  
                                  Component.propTypes = { /*Definition */};  

                                    ReactJS Props Validator

                                    ReactJS props validator contains the following list of validators.

                                    SNPropsTypeDescription
                                    1.PropTypes.anyThe props can be of any data type.
                                    2.PropTypes.arrayThe props should be an array.
                                    3.PropTypes.boolThe props should be a boolean.
                                    4.PropTypes.funcThe props should be a function.
                                    5.PropTypes.numberThe props should be a number.
                                    6.PropTypes.objectThe props should be an object.
                                    7.PropTypes.stringThe props should be a string.
                                    8.PropTypes.symbolThe props should be a symbol.
                                    9.PropTypes.instanceOfThe props should be an instance of a particular JavaScript class.
                                    10.PropTypes.isRequiredThe props must be provided.
                                    11.PropTypes.elementThe props must be an element.
                                    12.PropTypes.nodeThe props can render anything: numbers, strings, elements or an array (or fragment) containing these types.
                                    13.PropTypes.oneOf()The props should be one of several types of specific values.
                                    14.PropTypes.oneOfType([PropTypes.string,PropTypes.number])The props should be an object that could be one of many types.

                                    Example

                                    Here, we are creating an App component which contains all the props that we need. In this example, App.propTypes is used for props validation. For props validation, you must have to add this line: import PropTypes from ‘prop-types’ in App.js file.

                                    App.js

                                    import React, { Component } from 'react';  
                                    
                                    import PropTypes from 'prop-types';  
                                    
                                    class App extends React.Component {  
                                    
                                       render() {  
                                    
                                          return (  
                                    
                                              <div>  
                                    
                                                  <h1>ReactJS Props validation example</h1>  
                                    
                                                  <table>  
                                    
                                                      <tr>  
                                    
                                                          <th>Type</th>  
                                    
                                                          <th>Value</th>  
                                    
                                                          <th>Valid</th>  
                                    
                                                      </tr>  
                                    
                                                    <tr>  
                                    
                                                          <td>Array</td>  
                                    
                                                          <td>{this.props.propArray}</td>  
                                    
                                                          <td>{this.props.propArray ? "true" : "False"}</td>  
                                    
                                                      </tr>  
                                    
                                                      <tr>  
                                    
                                                          <td>Boolean</td>  
                                    
                                                          <td>{this.props.propBool ? "true" : "False"}</td>  
                                    
                                                          <td>{this.props.propBool ? "true" : "False"}</td>  
                                    
                                                      </tr>  
                                    
                                                      <tr>  
                                    
                                                          <td>Function</td>  
                                    
                                                          <td>{this.props.propFunc(5)}</td>  
                                    
                                                          <td>{this.props.propFunc(5) ? "true" : "False"}</td>  
                                    
                                                      </tr>  
                                    
                                                      <tr>  
                                    
                                                          <td>String</td>  
                                    
                                                          <td>{this.props.propString}</td>  
                                    
                                                          <td>{this.props.propString ? "true" : "False"}</td>  
                                    
                                                      </tr>  
                                    
                                                      <tr>  
                                    
                                                          <td>Number</td>  
                                    
                                                          <td>{this.props.propNumber}</td>  
                                    
                                                          <td>{this.props.propNumber ? "true" : "False"}</td>  
                                    
                                                      </tr>  
                                    
                                                 </table>  
                                    
                                            </div>  
                                    
                                            );  
                                    
                                       }  
                                    
                                    }  
                                    
                                    App.propTypes = {  
                                    
                                        propArray: PropTypes.array.isRequired,  
                                    
                                        propBool: PropTypes.bool.isRequired,  
                                    
                                        propFunc: PropTypes.func,  
                                    
                                        propNumber: PropTypes.number,  
                                    
                                        propString: PropTypes.string,   
                                    
                                    }  
                                    
                                    App.defaultProps = {  
                                    
                                        propArray: [1,2,3,4,5],  
                                    
                                        propBool: true,  
                                    
                                        propFunc: function(x){return x+5},  
                                    
                                        propNumber: 1,  
                                    
                                        propString: "JavaTpoint",  
                                    
                                    }  
                                    
                                    export default App;

                                    Main.js

                                    import React from 'react';  
                                    
                                    import ReactDOM from 'react-dom';  
                                    
                                    import App from './App.js';  
                                    
                                      
                                    
                                    ReactDOM.render(<App/>, document.getElementById('app')); 

                                      Output:

                                      React Props Validation

                                      ReactJS Custom Validators

                                      ReactJS allows creating a custom validation function to perform custom validation. The following argument is used to create a custom validation function.

                                      • props: It should be the first argument in the component.
                                      • propName: It is the propName that is going to validate.
                                      • componentName: It is the componentName that are going to validated again.

                                      Example

                                      var Component = React.createClass({  
                                      
                                      App.propTypes = {  
                                      
                                         customProp: function(props, propName, componentName) {  
                                      
                                              if (!item.isValid(props[propName])) {  
                                      
                                                return new Error('Validation failed!');  
                                      
                                              }  
                                      
                                            }  
                                      
                                         }  
                                      
                                      }) 
                                      1. Props

                                        Props stand for “Properties.” They are read-only components. It is an object which stores the value of attributes of a tag and work similar to the HTML attributes. It gives a way to pass data from one component to other components. It is similar to function arguments. Props are passed to the component in the same way as arguments passed in a function.

                                        Props are immutable so we cannot modify the props from inside the component. Inside the components, we can add attributes called props. These attributes are available in the component as this.props and can be used to render dynamic data in our render method.

                                        When you need immutable data in the component, you have to add props to reactDom.render() method in the main.js file of your ReactJS project and used it inside the component in which you need. It can be explained in the below example.

                                        Example

                                        App.js

                                        import React, { Component } from 'react';  
                                        
                                        class App extends React.Component {  
                                        
                                           render() {     
                                        
                                              return (  
                                        
                                                  <div>  
                                        
                                                    <h1> Welcome to { this.props.name } </h1>    
                                        
                                                    <p> <h4> Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. </h4> </p>          
                                        
                                                  </div>  
                                        
                                              );  
                                        
                                           }  
                                        
                                        }  
                                        
                                        export default App; 

                                          Main.js

                                          import React from 'react';  
                                          
                                          import ReactDOM from 'react-dom';  
                                          
                                          import App from './App.js';  
                                          
                                            
                                          
                                          ReactDOM.render(<App name = "JavaTpoint!!" />, document.getElementById('app')); 

                                            Output

                                            ReactJS Props

                                            Default Props

                                            It is not necessary to always add props in the reactDom.render() element. You can also set default props directly on the component constructor. It can be explained in the below example.

                                            Example

                                            App.js

                                            import React, { Component } from 'react';  
                                            
                                            class App extends React.Component {  
                                            
                                               render() {     
                                            
                                                  return (  
                                            
                                                      <div>  
                                            
                                                          <h1>Default Props Example</h1>  
                                            
                                                        <h3>Welcome to {this.props.name}</h3>   
                                            
                                                        <p>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad.</p>          
                                            
                                                      </div>  
                                            
                                                    );  
                                            
                                                }  
                                            
                                            }  
                                            
                                            App.defaultProps = {  
                                            
                                               name: "JavaTpoint"  
                                            
                                            }  
                                            
                                            export default App;  

                                              Main.js

                                              import React from 'react';  
                                              
                                              import ReactDOM from 'react-dom';  
                                              
                                              import App from './App.js';  
                                              
                                                
                                              
                                              ReactDOM.render(<App/>, document.getElementById('app'));

                                              Output

                                              ReactJS Props

                                              State and Props

                                              It is possible to combine both state and props in your app. You can set the state in the parent component and pass it in the child component using props. It can be shown in the below example.

                                              Example

                                              App.js

                                              import React, { Component } from 'react';  
                                              
                                              class App extends React.Component {  
                                              
                                                 constructor(props) {  
                                              
                                                    super(props);  
                                              
                                                    this.state = {  
                                              
                                                       name: "JavaTpoint",         
                                              
                                                    }  
                                              
                                                 }  
                                              
                                                 render() {  
                                              
                                                    return (  
                                              
                                                       <div>  
                                              
                                                          <JTP jtpProp = {this.state.name}/>             
                                              
                                                       </div>  
                                              
                                                    );  
                                              
                                                 }  
                                              
                                              }  
                                              
                                              class JTP extends React.Component {  
                                              
                                                 render() {  
                                              
                                                    return (  
                                              
                                                        <div>  
                                              
                                                            <h1>State & Props Example</h1>  
                                              
                                                            <h3>Welcome to {this.props.jtpProp}</h3>  
                                              
                                                            <p>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad.</p>  
                                              
                                                       </div>    
                                              
                                                    );  
                                              
                                                 }  
                                              
                                              }  
                                              
                                              export default App; 

                                                Main.js

                                                import React from 'react';  
                                                
                                                import ReactDOM from 'react-dom';  
                                                
                                                import App from './App.js';  
                                                
                                                  
                                                
                                                ReactDOM.render(<App/>, document.getElementById('app'));

                                                Output:

                                                ReactJS Props
                                              1. State

                                                The state is an updatable structure that is used to contain data or information about the component. The state in a component can change over time. The change in state over time can happen as a response to user action or system event. A component with the state is known as stateful components. It is the heart of the react component which determines the behavior of the component and how it will render. They are also responsible for making a component dynamic and interactive.

                                                A state must be kept as simple as possible. It can be set by using the setState() method and calling setState() method triggers UI updates. A state represents the component’s local state or information. It can only be accessed or modified inside the component or by the component directly. To set an initial state before any interaction occurs, we need to use the getInitialState() method.

                                                For example, if we have five components that need data or information from the state, then we need to create one container component that will keep the state for all of them.

                                                Defining State

                                                To define a state, you have to first declare a default set of values for defining the component’s initial state. To do this, add a class constructor which assigns an initial state using this.state. The ‘this.state‘ property can be rendered inside render() method.

                                                Example

                                                The below sample code shows how we can create a stateful component using ES6 syntax.

                                                import React, { Component } from 'react';  
                                                
                                                class App extends React.Component {  
                                                
                                                 constructor() {  
                                                
                                                      super();        
                                                
                                                      this.state = { displayBio: true };  
                                                
                                                      }  
                                                
                                                      render() {  
                                                
                                                          const bio = this.state.displayBio ? (  
                                                
                                                              <div>  
                                                
                                                                  <p><h3>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students.</h3></p>   
                                                
                                                            </div>  
                                                
                                                              ) : null;  
                                                
                                                              return (  
                                                
                                                                  <div>  
                                                
                                                                      <h1> Welcome to JavaTpoint!! </h1>  
                                                
                                                                      { bio }   
                                                
                                                                  </div>  
                                                
                                                              );  
                                                
                                                     }  
                                                
                                                }  
                                                
                                                export default App;  

                                                  To set the state, it is required to call the super() method in the constructor. It is because this.state is uninitialized before the super() method has been called.

                                                  Output

                                                  ReactJS State

                                                  Changing the State

                                                  We can change the component state by using the setState() method and passing a new state object as the argument. Now, create a new method toggleDisplayBio() in the above example and bind this keyword to the toggleDisplayBio() method otherwise we can’t access this inside toggleDisplayBio() method.

                                                  this.toggleDisplayBio = this.toggleDisplayBio.bind(this);  

                                                  Example

                                                  In this example, we are going to add a button to the render() method. Clicking on this button triggers the toggleDisplayBio() method which displays the desired output.

                                                  import React, { Component } from 'react';  
                                                  
                                                  class App extends React.Component {  
                                                  
                                                   constructor() {  
                                                  
                                                        super();        
                                                  
                                                        this.state = { displayBio: false };  
                                                  
                                                        console.log('Component this', this);  
                                                  
                                                        this.toggleDisplayBio = this.toggleDisplayBio.bind(this);  
                                                  
                                                        }  
                                                  
                                                        toggleDisplayBio(){  
                                                  
                                                            this.setState({displayBio: !this.state.displayBio});  
                                                  
                                                            }  
                                                  
                                                        render() {  
                                                  
                                                            return (  
                                                  
                                                                <div>  
                                                  
                                                                    <h1>Welcome to JavaTpoint!!</h1>  
                                                  
                                                                    {  
                                                  
                                                                        this.state.displayBio ? (   
                                                  
                                                                            <div>  
                                                  
                                                                                <p><h4>Javatpoint is one of the best Java training institute in Noida, Delhi, Gurugram, Ghaziabad and Faridabad. We have a team of experienced Java developers and trainers from multinational companies to teach our campus students.</h4></p>  
                                                  
                                                                                <button onClick={this.toggleDisplayBio}> Show Less </button>  
                                                  
                                                                          </div>  
                                                  
                                                                            ) : (  
                                                  
                                                                                <div>  
                                                  
                                                                                    <button onClick={this.toggleDisplayBio}> Read More </button>  
                                                  
                                                                                </div>  
                                                  
                                                                            )  
                                                  
                                                                    }  
                                                  
                                                               </div>  
                                                  
                                                          )  
                                                  
                                                      }  
                                                  
                                                  }  
                                                  
                                                  export default App;  

                                                    Output:

                                                    ReactJS State

                                                    When you click the Read More button, you will get the below output, and when you click the Show Less button, you will get the output as shown in the above image.

                                                    ReactJS State