Author: saqibkhan

  • Overview

    Laravel is an open-source PHP framework, which is robust and easy to understand. It follows a model-view-controller design pattern. Laravel reuses the existing components of different frameworks which helps in creating a web application. The web application thus designed is more structured and pragmatic.

    Laravel offers a rich set of functionalities which incorporates the basic features of PHP frameworks like CodeIgniter, Yii and other programming languages like Ruby on Rails. Laravel has a very rich set of features which will boost the speed of web development.

    If you are familiar with Core PHP and Advanced PHP, Laravel will make your task easier. It saves a lot time if you are planning to develop a website from scratch. Moreover, a website built in Laravel is secure and prevents several web attacks.

    Advantages of Laravel

    Laravel offers you the following advantages, when you are designing a web application based on it −

    • The web application becomes more scalable, owing to the Laravel framework.
    • Considerable time is saved in designing the web application, since Laravel reuses the components from other framework in developing web application.
    • It includes namespaces and interfaces, thus helps to organize and manage resources.

    Composer

    Composer is a tool which includes all the dependencies and libraries. It allows a user to create a project with respect to the mentioned framework (for example, those used in Laravel installation). Third party libraries can be installed easily with help of composer.

    All the dependencies are noted in composer.json file which is placed in the source folder.

    Artisan

    Command line interface used in Laravel is called Artisan. It includes a set of commands which assists in building a web application. These commands are incorporated from Symphony framework, resulting in add-on features in Laravel 5.1 (latest version of Laravel).

    Features of Laravel

    Laravel offers the following key features which makes it an ideal choice for designing web applications −

    Modularity

    Laravel provides 20 built in libraries and modules which helps in enhancement of the application. Every module is integrated with Composer dependency manager which eases updates.

    Testability

    Laravel includes features and helpers which helps in testing through various test cases. This feature helps in maintaining the code as per the requirements.

    Routing

    Laravel provides a flexible approach to the user to define routes in the web application. Routing helps to scale the application in a better way and increases its performance.

    Configuration Management

    A web application designed in Laravel will be running on different environments, which means that there will be a constant change in its configuration. Laravel provides a consistent approach to handle the configuration in an efficient way.

    Query Builder and ORM

    Laravel incorporates a query builder which helps in querying databases using various simple chain methods. It provides ORM (Object Relational Mapper) and ActiveRecord implementation called Eloquent.

    Schema Builder

    Schema Builder maintains the database definitions and schema in PHP code. It also maintains a track of changes with respect to database migrations.

    Template Engine

    Laravel uses the Blade Template engine, a lightweight template language used to design hierarchical blocks and layouts with predefined blocks that include dynamic content.

    E-mail

    Laravel includes a mail class which helps in sending mail with rich content and attachments from the web application.

    Authentication

    User authentication is a common feature in web applications. Laravel eases designing authentication as it includes features such as register, forgot password and send password reminders.

    Redis

    Laravel uses Redis to connect to an existing session and general-purpose cache. Redis interacts with session directly.

    Queues

    Laravel includes queue services like emailing large number of users or a specified Cron job. These queues help in completing tasks in an easier manner without waiting for the previous task to be completed.

    Event and Command Bus

    Laravel 5.1 includes Command Bus which helps in executing commands and dispatch events in a simple way. The commands in Laravel act as per the application’s lifecycle.

  • Routing

    Laravel’s routing system is straightforward and expressive. You can define routes in a simple way, allowing for easy management of your application’s URL structure. This flexibility helps in creating clean and SEO-friendly URLs.

  • Eloquent ORM

    Eloquent is Laravel’s built-in Object-Relational Mapping (ORM) system, which simplifies database interactions. It allows developers to interact with the database using PHP syntax instead of raw SQL, making queries more intuitive and reducing the likelihood of errors.

  • MVC Architecture

    Laravel employs the Model-View-Controller (MVC) design pattern, which separates application logic from the user interface. This separation enhances organization, making the codebase easier to manage and maintain, and improves collaboration among developers.

  • Error Boundaries

    In the past, if we get any JavaScript errors inside components, it corrupts the React?s internal state and put React in a broken state on next renders. There are no ways to handle these errors in React components, nor it provides any methods to recover from them. But, React 16 introduces a new concept to handle the errors by using the error boundaries. Now, if any JavaScript error found in a part of the UI, it does not break the whole app.

    Error boundaries are React components which catch JavaScript errors anywhere in our app, log those errors, and display a fallback UI. It does not break the whole app component tree and only renders the fallback UI whenever an error occurred in a component. Error boundaries catch errors during rendering in component lifecycle methods, and constructors of the whole tree below them.Note:

    Sometimes, it is not possible to catch Error boundaries in React application. These are:

    • Event handlers
    • Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
    • Server-side rendering
    • Errors are thrown in the error boundary itself rather than its children.

    For simple React app, we can declare an error boundary once and can use it for the whole application. For a complex application which have multiple components, we can declare multiple error boundaries to recover each part of the entire application.

    We can also report the error to an error monitoring service like Rollbar. This monitoring service provides the ability to track how many users are affected by errors, find causes of them, and improve the user experience.

    Error boundary in class

    A class component can becomes an error boundary if it defines a new lifecycle methods either static getDerivedStateFromError() or componentDidCatch(error, info). We can use static getDerivedStateFromError() to render a fallback UI when an error has been thrown, and can use componentDidCatch() to log error information.

    An error boundary can?t catch the error within itself. If the error boundary fails to render the error message, the error will go to the closest error boundary above it. It is similar to the catch {} block in JavaScript.

    How to implement error boundaries

    Step-1 Create a class which extends React component and passes the props inside it.

    Step-2 Now, add componentDidCatch() method which allows you to catch error in the components below them in the tree.

    Step-3 Next add render() method, which is responsible for how the component should be rendered. For example, it will display the error message like “Something is wrong.”

    Example

    class ErrorBoundary extends React.Component {  
    
      constructor(props) {  
    
        super(props);  
    
        this.state = { hasError: false };  
    
      }  
    
      static getDerivedStateFromError(error) {  
    
        // It will update the state so the next render shows the fallback UI.  
    
        return { hasError: true };  
    
      }  
    
      componentDidCatch(error, info) {  
    
        // It will catch error in any component below. We can also log the error to an error reporting service.  
    
        logErrorToMyService(error, info);  
    
      }  
    
      render() {  
    
        if (this.state.hasError) {  
    
            return (  
    
            <div>Something is wrong.</div>;  
    
        );  
    
        }  
    
        return this.props.children;   
    
      }  
    
    } 

      Step-4 Now, we can use it as a regular component. Add the new component in HTML, which you want to include in the error boundary. In this example, we are adding an error boundary around a MyWidgetCounter component.

      <ErrorBoundary>  
      
             <MyWidgetCounter/>  
      
      </ErrorBoundary> 

        Where to Place Error Boundaries

        An error boundary entirely depends on you. You can use error boundaries on the top-level of the app components or wrap it on the individual components to protect them from breaking the other parts of the app.

        Let us see an example.

        import React from 'react';  
        
        import './App.css'  
        
          
        
        class ErrorBoundary extends React.Component {  
        
          constructor(props) {  
        
            super(props);  
        
            this.state = { error: false, errorInfo: null };  
        
          }  
        
            
        
          componentDidCatch(error, errorInfo) {  
        
            // Catch errors in any components below and re-render with error message  
        
            this.setState({  
        
              error: error,  
        
              errorInfo: errorInfo  
        
            })  
        
          }  
        
            
        
          render() {  
        
            if (this.state.errorInfo) {  
        
              return (  
        
                <div>  
        
                  <h2>Something went wrong.</h2>  
        
                  <details style={{ whiteSpace: 'pre-wrap' }}>  
        
                    {this.state.error && this.state.error.toString()}  
        
                    <br />  
        
                    {this.state.errorInfo.componentStack}  
        
                  </details>  
        
                </div>  
        
              );  
        
            }  
        
            return this.props.children;  
        
          }    
        
        }  
        
          
        
        class BuggyCounter extends React.Component {  
        
          constructor(props) {  
        
            super(props);  
        
            this.state = { counter: 0 };  
        
            this.handleClick = this.handleClick.bind(this);  
        
          }  
        
            
        
          handleClick() {  
        
            this.setState(({counter}) => ({  
        
              counter: counter + 1  
        
            }));  
        
          }  
        
            
        
          render() {  
        
            if (this.state.counter === 3) {  
        
              throw new Error('I crashed!');  
        
            }  
        
            return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;  
        
          }  
        
        }  
        
          
        
        function App() {  
        
          return (  
        
            <div>  
        
              <p><b>Example of Error Boundaries</b></p>  
        
              <hr />  
        
              <ErrorBoundary>  
        
                <p>These two counters are inside the same error boundary.</p>  
        
                  <BuggyCounter />  
        
                  <BuggyCounter />  
        
              </ErrorBoundary>  
        
              <hr />  
        
              <p>These two counters are inside of their individual error boundary.</p>  
        
                <ErrorBoundary><BuggyCounter /></ErrorBoundary>  
        
                <ErrorBoundary><BuggyCounter /></ErrorBoundary>  
        
            </div>  
        
          );  
        
        }  
        
        export default App  

          In the above code snippet, when we click on the numbers, it increases the counters. The counter is programmed to throw an error when it reaches 3. It simulates a JavaScript error in a component. Here, we used an error boundary in two ways, which are given below.

          First, these two counters are inside the same error boundary. If anyone crashes, the error boundary will replace both of them.

          <ErrorBoundary>  
          
                    <BuggyCounter />  
          
                    <BuggyCounter />  
          
          </ErrorBoundary>  

            Second, these two counters are inside of their individual error boundary. So if anyone crashes, the other is not affected.

            <ErrorBoundary><BuggyCounter /></ErrorBoundary>  
            
            <ErrorBoundary><BuggyCounter /></ErrorBoundary>

            Output:

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

            React Error Boundaries

            When the counter has reached at 3, it gives the following output.

            React Error Boundaries

            New Behavior for Uncaught error

            It is an important implication related to error boundaries. If the error does not catch by any error boundary, it will result in unmounting of the whole React application.

            Error Boundary in Event Handler

            Error boundaries do not allow catching errors inside event handlers. React does not need any error boundary to recover from errors in the event handler. If there is a need to catch errors in the event handler, you can use JavaScript try-catch statement.

            In the below example, you can see how an event handler will handle the errors.

            class MyComponent extends React.Component {  
            
              constructor(props) {  
            
                super(props);  
            
                this.state = { error: null };  
            
                this.handleClick = this.handleClick.bind(this);  
            
              }  
            
              
            
              handleClick() {  
            
                try {  
            
                  // Do something which can throw error  
            
                } catch (error) {  
            
                  this.setState({ error });  
            
                }  
            
              }  
            
              
            
              render() {  
            
                if (this.state.error) {  
            
                  return   
            
                      <h2>It caught an error.</h2>  
            
                }  
            
                return <div onClick={this.handleClick}>Click Me</div>  
            
              }  
            
            } 
            1. Portals

              The React 16.0 version introduced React portals in September 2017. A React portal provides a way to render an element outside of its component hierarchy, i.e., in a separate component.

              Before React 16.0 version, it is very tricky to render the child component outside of its parent component hierarchy. If we do this, it breaks the convention where a component needs to render as a new element and follow a parent-child hierarchy. In React, the parent component always wants to go where its child component goes. That’s why React portal concept comes in.

              Syntax

              ReactDOM.createPortal(child, container)  

              Here, the first argument (child) is the component, which can be an element, string, or fragment, and the second argument (container) is a DOM element.

              Example before React v16

              Generally, when you want to return an element from a component’s render method, it is mounted as a new div into the DOM and render the children of the closest parent component.

              render() {  
              
              // React mounts a new div into the DOM and renders the children into it  
              
                return (  
              
                 <div>  
              
                   {this.props.children}  
              
                 </div>  
              
                );  
              
              }  

                Example using portal

                But, sometimes we want to insert a child component into a different location in the DOM. It means React does not want to create a new div. We can do this by creating React portal.

                render() {  
                
                 return ReactDOM.createPortal(  
                
                   this.props.children,  
                
                   myNode,  
                
                 );  
                
                }  

                  Features

                  • It uses React version 16 and its official API for creating portals.
                  • It has a fallback for React version 15.
                  • It transports its children component into a new React portal which is appended by default to document.body.
                  • It can also target user specified DOM element.
                  • It supports server-side rendering
                  • It supports returning arrays (no wrapper div’s needed)
                  • It uses <Portal /> and <PortalWithState /> so there is no compromise between flexibility and convenience.
                  • It doesn’t produce any DOM mess.
                  • It has no dependencies, minimalistic.

                  When to use?

                  The common use-cases of React portal include:

                  • Modals
                  • Tooltips
                  • Floating menus
                  • Widgets

                  Installation

                  We can install React portal using the following command.

                  $ npm install react-portal --save  

                  Explanation of React Portal

                  Create a new React project using the following command.

                  $ npx create-react-app reactapp  

                  Open the App.js file and insert the following code snippet.

                  App.js

                  import React, {Component} from 'react';    
                  
                  import './App.css'  
                  
                  import PortalDemo from './PortalDemo.js';  
                  
                    
                  
                  class App extends Component {    
                  
                      render () {    
                  
                          return (    
                  
                              <div className='App'>  
                  
                           <PortalDemo />  
                  
                      </div>    
                  
                          );    
                  
                      }    
                  
                  }    
                  
                  export default App;

                  The next step is to create a portal component and import it in the App.js file.

                  PortalDemo.js

                  import React from 'react'  
                  
                  import ReactDOM from 'react-dom'  
                  
                    
                  
                  function PortalDemo(){  
                  
                      return ReactDOM.createPortal(  
                  
                        <h1>Portals Demo</h1>,  
                  
                        document.getElementById('portal-root')  
                  
                      )  
                  
                  }  
                  
                  export default PortalDemo  

                    Now, open the Index.html file and add a <div id=”portal-root”></div> element to access the child component outside the root node.

                    Index.html

                    <!DOCTYPE html>  
                    
                    <html lang="en">  
                    
                      <head>  
                    
                        <meta charset="utf-8" />  
                    
                        <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />  
                    
                        <meta name="viewport" content="width=device-width, initial-scale=1" />  
                    
                        <meta name="theme-color" content="#000000" />  
                    
                        <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />  
                    
                        <title>React App</title>  
                    
                      </head>  
                    
                      <body>  
                    
                        <noscript>It is required to enable JavaScript to run this app.</noscript>  
                    
                        <div id="root"></div>  
                    
                        <div id="portal-root"></div>  
                    
                      </body>  
                    
                    </html> 

                      Output:

                      When we execute the React app, we will get the following screen.

                      React Portal

                      Now, open the Inspect (ctrl + shift + I). In this window, select the Elements section and then click on the <div id=”portal-root”></div> component. Here, we can see that each tag is under the “portal-root” DOM node, not the “root” DOM node. Hence, we can see that how React Portal provides the ability to break out of root DOM tree.

                      React Portal
                    1. Redux Example

                      In this section, we will learn how to implements Redux in React application. Here, we provide a simple example to connect Redux and React.

                      Step-1 Create a new react project using create-react-app command. I choose the project name: “reactproject.” Now, install Redux and React-Redux.

                      javatpoint@root:~/Desktop$ npx create-react-app reactproject  
                      
                      javatpoint@root:~/Desktop/reactproject$ npm install redux react-redux --save 

                        Step-2 Create Files and Folders

                        In this step, we need to create folders and files for actions, reducers, components, and containers. After creating folders and files, our project looks like as below image.

                        React Redux Example

                        Step-3 Actions

                        It uses ‘type‘ property to inform about data that should be sent to the Store. In this folder, we will create two files: index.js and index.spec.js. Here, we have created an action creator that returns our action and sets an id for every created item.

                        Index.js

                        let nextTodoId = 0  
                        
                        export const addTodo = text => ({  
                        
                          type: 'ADD_TODO',  
                        
                          id: nextTodoId++,  
                        
                          text  
                        
                        })  
                        
                          
                        
                        export const setVisibilityFilter = filter => ({  
                        
                          type: 'SET_VISIBILITY_FILTER',  
                        
                          filter  
                        
                        })  
                        
                          
                        
                        export const toggleTodo = id => ({  
                        
                          type: 'TOGGLE_TODO',  
                        
                          id  
                        
                        })  
                        
                          
                        
                        export const VisibilityFilters = {  
                        
                          SHOW_ALL: 'SHOW_ALL',  
                        
                          SHOW_COMPLETED: 'SHOW_COMPLETED',  
                        
                          SHOW_ACTIVE: 'SHOW_ACTIVE'  
                        
                        } 

                          Index.spec.js

                          import * as actions from './index'  
                          
                            
                          
                          describe('todo actions', () => {  
                          
                            it('addTodo should create ADD_TODO action', () => {  
                          
                              expect(actions.addTodo('Use Redux')).toEqual({  
                          
                                type: 'ADD_TODO',  
                          
                                id: 0,  
                          
                                text: 'Use Redux'  
                          
                              })  
                          
                            })  
                          
                            
                          
                            it('setVisibilityFilter should create SET_VISIBILITY_FILTER action', () => {  
                          
                              expect(actions.setVisibilityFilter('active')).toEqual({  
                          
                                type: 'SET_VISIBILITY_FILTER',  
                          
                                filter: 'active'  
                          
                              })  
                          
                            })  
                          
                            
                          
                            it('toggleTodo should create TOGGLE_TODO action', () => {  
                          
                              expect(actions.toggleTodo(1)).toEqual({  
                          
                                type: 'TOGGLE_TODO',  
                          
                                id: 1  
                          
                              })  
                          
                            })  
                          
                          })

                          Step-4 Reducers

                          As we know, Actions only trigger changes in the app, and the Reducers specify those changes. The Reducer is a function which takes two parameters ‘Action’ and ‘State’ to calculate and return an updated State. It read the payloads from the ‘Actions’ and then updates the ‘Store’ via the State accordingly.

                          In the given files, each Reducer managing its own part of the global State. The State parameter is different for every Reducer and corresponds to the part of the ‘State’ it manages. When the app becomes larger, we can split the Reducers into separate files and keep them completely independent and managing different data domains.

                          Here, we are using ‘combineReducers’ helper function to add any new Reducers we might use in the future.

                          index.js

                          import { combineReducers } from 'redux'  
                          
                          import todos from './todos'  
                          
                          import visibilityFilter from './visibilityFilter'  
                          
                            
                          
                          export default combineReducers({  
                          
                            todos,  
                          
                            visibilityFilter  
                          
                          }) 

                            Todos.js

                            const todos = (state = [], action) => {  
                            
                              switch (action.type) {  
                            
                                case 'ADD_TODO':  
                            
                                  return [  
                            
                                    ...state,  
                            
                                    {  
                            
                                      id: action.id,  
                            
                                      text: action.text,  
                            
                                      completed: false  
                            
                                    }  
                            
                                  ]  
                            
                                case 'TOGGLE_TODO':  
                            
                                  return state.map(todo =>  
                            
                                    (todo.id === action.id)  
                            
                                      ? {...todo, completed: !todo.completed}  
                            
                                      : todo  
                            
                                  )  
                            
                                default:  
                            
                                  return state  
                            
                              }  
                            
                            }  
                            
                            export default todos 

                              Todos.spec.js

                              import todos from './todos'  
                              
                                
                              
                              describe('todos reducer', () => {  
                              
                                it('should handle initial state', () => {  
                              
                                  expect(  
                              
                                    todos(undefined, {})  
                              
                                  ).toEqual([])  
                              
                                })  
                              
                                
                              
                                it('should handle ADD_TODO', () => {  
                              
                                  expect(  
                              
                                    todos([], {  
                              
                                      type: 'ADD_TODO',  
                              
                                      text: 'Run the tests',  
                              
                                      id: 0  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }  
                              
                                  ])  
                              
                                
                              
                                  expect(  
                              
                                    todos([  
                              
                                      {  
                              
                                        text: 'Run the tests',  
                              
                                        completed: false,  
                              
                                        id: 0  
                              
                                      }  
                              
                                    ], {  
                              
                                      type: 'ADD_TODO',  
                              
                                      text: 'Use Redux',  
                              
                                      id: 1  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }, {  
                              
                                      text: 'Use Redux',  
                              
                                      completed: false,  
                              
                                      id: 1  
                              
                                    }  
                              
                                  ])  
                              
                                
                              
                                  expect(  
                              
                                    todos([  
                              
                                      {  
                              
                                        text: 'Run the tests',  
                              
                                        completed: false,  
                              
                                        id: 0  
                              
                                      }, {  
                              
                                        text: 'Use Redux',  
                              
                                        completed: false,  
                              
                                        id: 1  
                              
                                      }  
                              
                                    ], {  
                              
                                      type: 'ADD_TODO',  
                              
                                      text: 'Fix the tests',  
                              
                                      id: 2  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }, {  
                              
                                      text: 'Use Redux',  
                              
                                      completed: false,  
                              
                                      id: 1  
                              
                                    }, {  
                              
                                      text: 'Fix the tests',  
                              
                                      completed: false,  
                              
                                      id: 2  
                              
                                    }  
                              
                                  ])  
                              
                                })  
                              
                                
                              
                                it('should handle TOGGLE_TODO', () => {  
                              
                                  expect(  
                              
                                    todos([  
                              
                                      {  
                              
                                        text: 'Run the tests',  
                              
                                        completed: false,  
                              
                                        id: 1  
                              
                                      }, {  
                              
                                        text: 'Use Redux',  
                              
                                        completed: false,  
                              
                                        id: 0  
                              
                                      }  
                              
                                    ], {  
                              
                                      type: 'TOGGLE_TODO',  
                              
                                      id: 1  
                              
                                    })  
                              
                                  ).toEqual([  
                              
                                    {  
                              
                                      text: 'Run the tests',  
                              
                                      completed: true,  
                              
                                      id: 1  
                              
                                    }, {  
                              
                                      text: 'Use Redux',  
                              
                                      completed: false,  
                              
                                      id: 0  
                              
                                    }  
                              
                                  ])  
                              
                                })  
                              
                              })  

                                VisibilityFilter.js

                                import { VisibilityFilters } from '../actions'  
                                
                                  
                                
                                const visibilityFilter = (state = VisibilityFilters.SHOW_ALL, action) => {  
                                
                                  switch (action.type) {  
                                
                                    case 'SET_VISIBILITY_FILTER':  
                                
                                      return action.filter  
                                
                                    default:  
                                
                                      return state  
                                
                                  }  
                                
                                }  
                                
                                export default visibilityFilter  

                                  Step-5 Components

                                  It is a Presentational Component, which concerned with how things look such as markup, styles. It receives data and invokes callbacks exclusively via props. It does not know where the data comes from or how to change it. It only renders what is given to them.

                                  App.js

                                  It is the root component which renders everything in the UI.

                                  import React from 'react'  
                                  
                                  import Footer from './Footer'  
                                  
                                  import AddTodo from '../containers/AddTodo'  
                                  
                                  import VisibleTodoList from '../containers/VisibleTodoList'  
                                  
                                    
                                  
                                  const App = () => (  
                                  
                                    <div>  
                                  
                                      <AddTodo />  
                                  
                                      <VisibleTodoList />  
                                  
                                      <Footer />  
                                  
                                    </div>  
                                  
                                  )  
                                  
                                  export default App 

                                    Footer.js

                                    It tells where the user changes currently visible todos.

                                    import React from 'react'  
                                    
                                    import FilterLink from '../containers/FilterLink'  
                                    
                                    import { VisibilityFilters } from '../actions'  
                                    
                                      
                                    
                                    const Footer = () => (  
                                    
                                      <p>  
                                    
                                        Show: <FilterLink filter={VisibilityFilters.SHOW_ALL}>All</FilterLink>  
                                    
                                        {', '}  
                                    
                                        <FilterLink filter={VisibilityFilters.SHOW_ACTIVE}>Active</FilterLink>  
                                    
                                        {', '}  
                                    
                                        <FilterLink filter={VisibilityFilters.SHOW_COMPLETED}>Completed</FilterLink>  
                                    
                                      </p>  
                                    
                                    )  
                                    
                                    export default Footer  

                                      Link.js

                                      It is a link with a callback.

                                        import React from 'react'  
                                      
                                      import PropTypes from 'prop-types'  
                                      
                                        
                                      
                                      const Link = ({ active, children, onClick }) => {  
                                      
                                        if (active) {  
                                      
                                          return <span>{children}</span>  
                                      
                                        }  
                                      
                                        
                                      
                                        return (  
                                      
                                          <a  
                                      
                                            href=""  
                                      
                                            onClick={e => {  
                                      
                                              e.preventDefault()  
                                      
                                              onClick()  
                                      
                                            }}  
                                      
                                          >  
                                      
                                            {children}  
                                      
                                          </a>  
                                      
                                        )  
                                      
                                      }  
                                      
                                        
                                      
                                      Link.propTypes = {  
                                      
                                        active: PropTypes.bool.isRequired,  
                                      
                                        children: PropTypes.node.isRequired,  
                                      
                                        onClick: PropTypes.func.isRequired  
                                      
                                      }  
                                      
                                        
                                      
                                      export default Link

                                        Todo.js

                                        It represents a single todo item which shows text.

                                        import React from 'react'  
                                        
                                        import PropTypes from 'prop-types'  
                                        
                                          
                                        
                                        const Todo = ({ onClick, completed, text }) => (  
                                        
                                          <li  
                                        
                                            onClick={onClick}  
                                        
                                            style={{  
                                        
                                              textDecoration: completed ? 'line-through' : 'none'  
                                        
                                            }}  
                                        
                                          >  
                                        
                                            {text}  
                                        
                                          </li>  
                                        
                                        )  
                                        
                                          
                                        
                                        Todo.propTypes = {  
                                        
                                          onClick: PropTypes.func.isRequired,  
                                        
                                          completed: PropTypes.bool.isRequired,  
                                        
                                          text: PropTypes.string.isRequired  
                                        
                                        }  
                                        
                                          
                                        
                                        export default Todo  

                                          TodoList.js

                                          It is a list to show visible todos{ id, text, completed }.

                                          import React from 'react'  
                                          
                                          import PropTypes from 'prop-types'  
                                          
                                          import Todo from './Todo'  
                                          
                                            
                                          
                                          const TodoList = ({ todos, onTodoClick }) => (  
                                          
                                            <ul>  
                                          
                                              {todos.map((todo, index) => (  
                                          
                                                <Todo key={index} {...todo} onClick={() => onTodoClick(index)} />  
                                          
                                              ))}  
                                          
                                            </ul>  
                                          
                                          )  
                                          
                                            
                                          
                                          TodoList.propTypes = {  
                                          
                                            todos: PropTypes.arrayOf(  
                                          
                                              PropTypes.shape({  
                                          
                                                id: PropTypes.number.isRequired,  
                                          
                                                completed: PropTypes.bool.isRequired,  
                                          
                                                text: PropTypes.string.isRequired  
                                          
                                              }).isRequired  
                                          
                                            ).isRequired,  
                                          
                                            onTodoClick: PropTypes.func.isRequired  
                                          
                                          }  
                                          
                                          export default TodoList

                                            Step-6 Containers

                                            It is a Container Component which concerned with how things work such as data fetching, updates State. It provides data and behavior to presentational components or other container components. It uses Redux State to read data and dispatch Redux Action for updating data.

                                            AddTodo.js

                                            It contains the input field with an ADD (submit) button.

                                            import React from 'react'  
                                            
                                            import { connect } from 'react-redux'  
                                            
                                            import { addTodo } from '../actions'  
                                            
                                              
                                            
                                            const AddTodo = ({ dispatch }) => {  
                                            
                                              let input  
                                            
                                              
                                            
                                              return (  
                                            
                                                <div>  
                                            
                                                  <form onSubmit={e => {  
                                            
                                                    e.preventDefault()  
                                            
                                                    if (!input.value.trim()) {  
                                            
                                                      return  
                                            
                                                    }  
                                            
                                                    dispatch(addTodo(input.value))  
                                            
                                                    input.value = ''  
                                            
                                                  }}>  
                                            
                                                    <input ref={node => input = node} />  
                                            
                                                    <button type="submit">  
                                            
                                                      Add Todo  
                                            
                                                    </button>  
                                            
                                                  </form>  
                                            
                                                </div>  
                                            
                                              )  
                                            
                                            }  
                                            
                                            export default connect()(AddTodo)  

                                              FilterLink.js

                                              It represents the current visibility filter and renders a link.

                                              import { connect } from 'react-redux'  
                                              
                                              import { setVisibilityFilter } from '../actions'  
                                              
                                              import Link from '../components/Link'  
                                              
                                                
                                              
                                              const mapStateToProps = (state, ownProps) => ({  
                                              
                                                active: ownProps.filter === state.visibilityFilter  
                                              
                                              })  
                                              
                                                
                                              
                                              const mapDispatchToProps = (dispatch, ownProps) => ({  
                                              
                                                onClick: () => dispatch(setVisibilityFilter(ownProps.filter))  
                                              
                                              })  
                                              
                                                
                                              
                                              export default connect(  
                                              
                                                mapStateToProps,  
                                              
                                                mapDispatchToProps  
                                              
                                              )(Link)  

                                                VisibleTodoList.js

                                                It filters the todos and renders a TodoList.

                                                import { connect } from 'react-redux'  
                                                
                                                import { toggleTodo } from '../actions'  
                                                
                                                import TodoList from '../components/TodoList'  
                                                
                                                import { VisibilityFilters } from '../actions'  
                                                
                                                  
                                                
                                                const getVisibleTodos = (todos, filter) => {  
                                                
                                                  switch (filter) {  
                                                
                                                    case VisibilityFilters.SHOW_ALL:  
                                                
                                                      return todos  
                                                
                                                    case VisibilityFilters.SHOW_COMPLETED:  
                                                
                                                      return todos.filter(t => t.completed)  
                                                
                                                    case VisibilityFilters.SHOW_ACTIVE:  
                                                
                                                      return todos.filter(t => !t.completed)  
                                                
                                                    default:  
                                                
                                                      throw new Error('Unknown filter: ' + filter)  
                                                
                                                  }  
                                                
                                                }  
                                                
                                                  
                                                
                                                const mapStateToProps = state => ({  
                                                
                                                  todos: getVisibleTodos(state.todos, state.visibilityFilter)  
                                                
                                                })  
                                                
                                                  
                                                
                                                const mapDispatchToProps = dispatch => ({  
                                                
                                                  toggleTodo: id => dispatch(toggleTodo(id))  
                                                
                                                })  
                                                
                                                  
                                                
                                                export default connect(  
                                                
                                                  mapStateToProps,  
                                                
                                                  mapDispatchToProps  
                                                
                                                )(TodoList) 

                                                  Step-7 Store

                                                  All container components need access to the Redux Store to subscribe to it. For this, we need to pass it(store) as a prop to every container component. However, it gets tedious. So we recommend using special React Redux component calledwhich make the store available to all container components without passing it explicitly. It used once when you render the root component.

                                                  index.js

                                                  import React from 'react'  
                                                  
                                                  import { render } from 'react-dom'  
                                                  
                                                  import { createStore } from 'redux'  
                                                  
                                                  import { Provider } from 'react-redux'  
                                                  
                                                  import App from './components/App'  
                                                  
                                                  import rootReducer from './reducers'  
                                                  
                                                    
                                                  
                                                  const store = createStore(rootReducer)  
                                                  
                                                    
                                                  
                                                  render(  
                                                  
                                                    <Provider store={store}>  
                                                  
                                                      <App />  
                                                  
                                                    </Provider>,  
                                                  
                                                    document.getElementById('root')  
                                                  
                                                  )  

                                                    Output

                                                    When we execute the application, it gives the output as below screen.

                                                    React Redux Example

                                                    Now, we will be able to add items in the list.

                                                    React Redux Example

                                                    The detailed explanation of React-Redux example can be shown here: https://redux.js.org/basics/usage-with-react.

                                                  1. Redux

                                                    Redux is an open-source JavaScript library used to manage application state. React uses Redux for building the user interface. It was first introduced by Dan Abramov and Andrew Clark in 2015.

                                                    React Redux is the official React binding for Redux. It allows React components to read data from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model. React Redux is conceptually simple. It subscribes to the Redux store, checks to see if the data which your component wants have changed, and re-renders your component.

                                                    Redux was inspired by Flux. Redux studied the Flux architecture and omitted unnecessary complexity.

                                                    • Redux does not have Dispatcher concept.
                                                    • Redux has an only Store whereas Flux has many Stores.
                                                    • The Action objects will be received and handled directly by Store.

                                                    Why use React Redux?

                                                    The main reason to use React Redux are:

                                                    • React Redux is the official UI bindings for react Application. It is kept up-to-date with any API changes to ensure that your React components behave as expected.
                                                    • It encourages good ‘React’ architecture.
                                                    • It implements many performance optimizations internally, which allows to components re-render only when it actually needs.

                                                    Redux Architecture

                                                    React Redux

                                                    The components of Redux architecture are explained below.

                                                    STORE: A Store is a place where the entire state of your application lists. It manages the status of the application and has a dispatch(action) function. It is like a brain responsible for all moving parts in Redux.

                                                    ACTION: Action is sent or dispatched from the view which are payloads that can be read by Reducers. It is a pure object created to store the information of the user’s event. It includes information such as type of action, time of occurrence, location of occurrence, its coordinates, and which state it aims to change.

                                                    REDUCER: Reducer read the payloads from the actions and then updates the store via the state accordingly. It is a pure function to return a new state from the initial state.

                                                    Redux Installation

                                                    Requirements: React Redux requires React 16.8.3 or later version.

                                                    To use React Redux with React application, you need to install the below command.

                                                    $ npm install redux react-redux --save  
                                                    React Redux
                                                  2. Flux Vs. MVC

                                                    MVC

                                                    MVC stands for Model View Controller. It is an architectural pattern used for developing the user interface. It divides the application into three different logical components: the Model, the View, and the Controller. It is first introduced in 1976 in the Smalltalk programming language. In MVC, each component is built to handle specific development aspect of an application. It is one of the most used web development frameworks to create scalable projects.

                                                    MVC Architecture

                                                    The MVC architecture contains the three components. These are:

                                                    • Model: It is responsible for maintaining the behavior and data of an application.
                                                    • View: It is used to display the model in the user interface.
                                                    • Controller: It acts as an interface between the Model and the View components. It takes user input, manipulates the data(model) and causes the view to update.
                                                    React Flux Vs. MVC

                                                    Flux

                                                    According to the official site, Flux is the application architecture that Facebook uses for building client-side web applications. It is an alternative to MVC architecture and other software design patterns for managing how data flows in the react application. It is the backbone of all React application. It is not a library nor a framework. It complements React as view and follows the concept of Unidirectional Data Flow model.

                                                    Flux Architecture has three major roles in dealing with data:

                                                    1. Dispatcher
                                                    2. Stores
                                                    3. Views (React components)
                                                    React Flux Vs. MVC

                                                    MVC Vs. Flux

                                                    SNMVCFLUX
                                                    1.It was introduced in 1976.It was introduced just a few years ago.
                                                    2.It supports Bi-directional data Flow model.It supports Uni-directional data flow model.
                                                    3.In this, data binding is the key.In this, events or actions are the keys.
                                                    4.It is synchronous.It is asynchronous.
                                                    5.Here, controllers handle everything(logic).Here, stores handle all logic.
                                                    6.It is hard to debug.It is easy to debug because it has common initiating point: Dispatcher.
                                                    7.It is difficult to understand as the project size increases.It is easy to understand.
                                                    8.Its maintainability is difficult as the project scope goes huge.Its maintainability is easy and reduces runtime errors.
                                                    9.Testing of application is difficult.Testing of application is easy.
                                                    10.Scalability is complex.It can be easily scalable.
                                                  3. Flux Concept

                                                    Flux is an application architecture that Facebook uses internally for building the client-side web application with React. It is not a library nor a framework. It is neither a library nor a framework. It is a kind of architecture that complements React as view and follows the concept of Unidirectional Data Flow model. It is useful when the project has dynamic data, and we need to keep the data updated in an effective manner. It reduces the runtime errors.

                                                    Flux applications have three major roles in dealing with data:

                                                    1. Dispatcher
                                                    2. Stores
                                                    3. Views (React components)

                                                    Here, you should not be confused with the Model-View-Controller (MVC) model. Although, Controllers exists in both, but Flux controller-views (views) found at the top of the hierarchy. It retrieves data from the stores and then passes this data down to their children. Additionally, action creators – dispatcher helper methods used to describe all changes that are possible in the application. It can be useful as a fourth part of the Flux update cycle.

                                                    Structure and Data Flow

                                                    React Flux Concept

                                                    In Flux application, data flows in a single direction(unidirectional). This data flow is central to the flux pattern. The dispatcher, stores, and views are independent nodes with inputs and outputs. The actions are simple objects that contain new data and type property. Now, let us look at the various components of flux architecture one by one.

                                                    Dispatcher

                                                    It is a central hub for the React Flux application and manages all data flow of your Flux application. It is a registry of callbacks into the stores. It has no real intelligence of its own, and simply acts as a mechanism for distributing the actions to the stores. All stores register itself and provide a callback. It is a place which handled all events that modify the store. When an action creator provides a new action to the dispatcher, all stores receive that action via the callbacks in the registry.

                                                    The dispatcher’s API has five methods. These are:

                                                    SNMethodsDescriptions
                                                    1.register()It is used to register a store’s action handler callback.
                                                    2.unregister()It is used to unregisters a store’s callback.
                                                    3.waitFor()It is used to wait for the specified callback to run first.
                                                    4.dispatch()It is used to dispatches an action.
                                                    5.isDispatching()It is used to checks if the dispatcher is currently dispatching an action.

                                                    Stores

                                                    It primarily contains the application state and logic. It is similar to the model in a traditional MVC. It is used for maintaining a particular state within the application, updates themselves in response to an action, and emit the change event to alert the controller view.

                                                    Views

                                                    It is also called as controller-views. It is located at the top of the chain to store the logic to generate actions and receive new data from the store. It is a React component listen to change events and receives the data from the stores and re-render the application.

                                                    Actions

                                                    The dispatcher method allows us to trigger a dispatch to the store and include a payload of data, which we call an action. It is an action creator or helper methods that pass the data to the dispatcher.

                                                    Advantage of Flux

                                                    • It is a unidirectional data flow model which is easy to understand.
                                                    • It is open source and more of a design pattern than a formal framework like MVC architecture.
                                                    • The flux application is easier to maintain.
                                                    • The flux application parts are decoupled.