Search

What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  But first, what is Component-based Architecture? Component-based Architecture In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. What is component? So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.Benefits of using Component Architecture There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.React Components React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? A very simple components looks something like this:import React from "react";  function Greeting({ name }) {    return < h1 >{`Hello ${name}`}</h1>;  }  ReactDOM.render(<Greeting name="Gully Boy" />, document.getElementById("root"));Alright. But<Greeting /> is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  JSX JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. It gives a syntax { <Any JS code >}, inside curly bracket, we can write JS code. But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. import React from "react";  function Greeting({ name }) {    return React.createElement("h1", null, `Hello ${name}`);  }  ReactDOM.render(  React.createElement("Greeting", { name: "Gully Boy" }, null),  document.getElementById("root")  ); React.create Element is part of React API which actually defines a React element. This data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  Classification of React Components Based on Interactivity Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. There are two types of components based on interactivity: Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component <Greeting name="John Smith" /> is a stateless component as it just renders the information (in this case name props) passed to it. Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:import React, {useState} from 'react';  function Counter() {  const [value, setValue] = useState(0);  const increment = () => {  setValue(value + 1);  }  const decrement = () => {  setValue(value - 1);  }  return (  <div>  <button type="button" onClick={increment}>Decrement</button>  <span>{value}</span>  <button type="button" onClick={decrement}>Decrement</button>  </div>  );  }  export default Counter;Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. Based on Programming Methodology There are two type of components based on Programming Methodology Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:import React from 'react';  class Greeting extends React.Component {  constructor(props) {  super(props);  }  render() {  return < h1 >{`Hello ${this.props.name}`}</h1>;  }  }  export default Greeting; Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. Based on Functionality There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.Component and its lifecycle In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  React lifecycle: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:constructor constructor(props) { super(props); // code here }getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // return updated state object or null  } render render() {  // code here  } componentDidMount componentDidMount() {  // code here  } Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:getDerivedState From Props static getDerivedStateFromProps(props, state) {  // code here  // returns updated state object or null  } should Component Update shouldComponentUpdate(prevProps, prevState) {  // code here  // returns true to re-render the component otherwise return false.   // default is true  } render render() {  // code here  } getSnapshot Before Update getSnapshotBeforeUpdate(prevProps, prevState) {  // code here  } component Did Update componentDidUpdate(prevProps, preState, snapshot) {  // code here  } Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:componentWillUnmount  componentWillUnmount() {  // code here  }Set up a React project As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. Create React project with CRA First check the NodeJS and NPM installation on machine by executing following command: node --version  npm --version  npx –version In case NodeJS is not install then download and install it from https://nodejs.org/en/. Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: npx create-react-app My First React Project NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: cd My First React Project npm start This would start a local server at port number 3000 and open default React page in browser.Understanding project generated by CRAAbove image shows the files and folder generated by CRA. let us go through it and understand: package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... public folder: All public assets will be present in public folder like index.html, image or logo etc... src folder: All our JS code including React components will be present in src folder. CRA configured our React project with all the needed tooling required for web development. It configured Webpack, dev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslint, react-testing-library for unit testing React components etc... src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. What type of React Component should I build in 2020 So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: Counter component code: import React, { useState } from "react";  import "./Counter.css";  function Counter() {  const [count, setCount] = useState(0);  const increment = () => {  const updatedCount = count + 1;  setCount(updatedCount);  };  const decrement = () => {  const updatedCount = count - 1;  setCount(updatedCount);  };  return (  <div className="counterContainer">  <button type="button" onClick={decrement}>  - </button>  <span>{count}</span>  <button type="button" onClick={increment}>  +  </button>  </div>  );  } export default Counter; Styles are added in Counter.css .counterContainer {  background-color: #fff;  font-size: 24px;  font-weight: 500;  border: 1px solid #0874ce;  border-radius: 3px;  box-shadow: 1px 1px 4px 0 #0084ff;  }  .counterContainer button {  outline: none;  border: none;  width: 50px;  height: 40px;  background-color: transparent;  font-size: 24px;  font-weight: 500;  cursor: pointer;  }  .counterContainer span {  color: #0084ff;  } We have created a fully functional counter component which can be used anywhere in React application.
Rated 4.0/5 based on 15 customer reviews

What Is a React Component? Write Your First React Component

7K
  • by Pavan kumar
  • 08th Aug, 2020
  • Last updated on 21st Aug, 2020
  • 8 mins read
What Is a React Component? Write Your First React Component

Prior to ReactJS, Popular frameworks like Angular and Ember were focused more towards model/view/controller like patterns known as MVC. These frameworks tried to provide more functionalities and solve most front-end development problems. ReactJS, however, chose to follow a different path, focusing primarily on views and how we can efficiently render views, thus popularising Component-based Architecture in web development.  

I wouldn’t go so far as to say the creators of ReactJS invented the Component-based Architecture pattern, but for sure they saw its benefits and helped popularize this pattern for web development.  

But first, what is Component-based Architecture? 

Component-based Architecture 

In web development, final output is a fully functional UI. According to component-based architecture, we should see the complete UI as a combination of multiple smaller, reusable, composable, functional components and we should approach the problem in similar fashion. We should build multiple small, composable, functional components which can work together as a complete solution. 

What is component? 

So, we understand that in component-based architecture, we are supposed to build plenty of smaller components. But what is a component and how does it look like? 

The word "component" in software industry means a software package, a service or any module which encapsulate a set of related functionalities. In the context of UI development, a component means a UI element or a collection of UI elements which together provide some set of functionalities. A component could be as small and simple as a heading component which is builtwith single H1 tag and its text or it could be as complex as accordion or tabbed navigation. ReactJS also encourages web developers to build smaller, reusable, composable components.

Benefits of using Component Architecture 

There are lot of discussions about the benefits of using Component Architecture. Some people feel that if we break down the UI in multiple components interacting with each other,then the code base will have too many components and will eventually make the project un-maintainable. But still, this architecture has following benefits: 

  • Reusability: It would always be great to avoid writing new code as much as we can and use the existing well tested functionalities. If we have collection of well tested reusable components then definitely, the overall output would be more robust. 
  • Faster Development: Reusing the same set of components will eventually take less time to develop a functionality. 
  • Composability: A big functionality is nothing but a collection of multiple small functionalities. Similarly, it is simpler to build a bigger functionality efficiently if we can compose multiple small components together. 
  • Less Maintainability: More reusability means less code and less code will always lead to less maintenance of code base.

React Components 

React component is basically a collection of one or many UI elements which renders a complete functionality. It can show different behaviours based on different parameters. In ReactJS, these parameters are knownas state of component and props passed to component. So how does a React component looks like? 

A very simple components looks something like this:

import React from "react"; 
function Greeting({ name }) { 
  return < h1 >{`Hello ${name}`}</h1>; 
} 
ReactDOM.render(<Greeting name="Gully Boy" />, document.getElementById("root"));

Alright. But<Greeting /> is not recognised by web browsers so won't it throw an error? Above code uses JSX (Syntax extension for JavaScript) and there are tools which actually converts JSX into something understandable by JavaScript engines of web browsers.  

JSX 

JSX is a library which allows us to write HTML (or XML) like syntax in JavaScript file. Then this code goes through a tool which converts it into something understandable by JavaScript engines. It allows us to write HTML in JS. Igives a syntax { <Any JS code >}, inside curly bracket, we can write JS code. 

But still how does the final React component looks like? Below code snippet is a final conversion of above Greeting component. 

import React from "react"; 
function Greeting({ name }) { 
  return React.createElement("h1", null, `Hello ${name}`); 
} 
ReactDOM.render( 
React.createElement("Greeting", { name: "Gully Boy" }, null), 
document.getElementById("root") 
); 

React.create Element is part of React API which actually defines a React elementThis data structure will be used by React to render the DOM element later. So now, we understand the need of JSX and benefits of using JSX, We will be using React components using JSX in rest of the article.  

Classification of React Components 

Based on Interactivity 

Before going into the classification, we need to understand what a state means in React component. state is information that a component itself maintains and which changes with time. The state affects the UI and/or the behaviour of the component. 

There are two types of components based on interactivity: 

  • Stateless Component: When a React componentdoesn't have its own state and it just renders based on the information passed to component (props) or a hardcoded information within the component then such components are called as stateless component. Such type of component doesn't provide any user interactivity with component. For Ex: above Greeting component <Greeting name="John Smith" /> is a stateless component as it just renders the information (in this case name props) passed to it. 

  • Stateful Component: There is other type of component which possesses state. This means based of the state behaviour of component changes. These types of components are known as stateful components. For Example a counter component below:

import React, {useState} from 'react'; 
function Counter() { 
const [value, setValue] = useState(0); 
const increment = () => { 
setValue(value + 1); 
} 
const decrement = () => { 
setValue(value - 1); 
} 
return ( 
<div> 
<button type="button" onClick={increment}>Decrement</button> 
<span>{value}</span> 
<button type="button" onClick={decrement}>Decrement</button> 
</div> 
); 
} 
export default Counter;

Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

Based on Programming Methodology 

Counter component has a state value which changes when user clicks on increment or decrement button. there is a span tag which displays the state value and it also gets updated based on user action. So this component is an example of stateful component. 

Based on Programming Methodology 

There are two type of components based on Programming Methodology 

  • Class based Component: A React component can be JavaScript class which implements render method of ReactJS and extends React.Component class. Generally if a component has any state or need to implement any React lifecycle method then we create a class based component. Class based componentmust implement the render lifecycle method which returns the JSX. Stateless component can also be implemented as class based component. For example, Above <Greeting /> component can be implemented as class based component like below:

import React from 'react'; 
class Greeting extends React.Component { 
constructor(props) { 
super(props); 
} 
render() { 
return < h1 >{`Hello ${this.props.name}`}</h1>; 
} 
} 
export default Greeting; 
  • Functional Component: A React component can be JavaScript function which returns JSX. Before Hooks which means before React v16.8, functional component was used only for building stateless component. Functional component takes props as argument and returns JSX. Writing functional code is always better in comparison to class based component because transpiled code for functional component is always shorter than class based component. For example, First implementation of <Greeting /> at the top is functional component. 

Based on Functionality 

There are two types of components categorised based on functionality. One typeimplementsbusiness logic and the other type is more inclined towards UI. 

  • Presentational Component: React components which decide the look and feel of UI are called presentational component. These components can be stateful or stateless components. State of these components are normally UI level state instead of application (business logic) state. These components are reusable and often used to have independent styles. For example: above Greeting component is a presentational component which can we be reused multiple places in application. 

  • Container Component: React component which mainly deals with application level state, rarely contains HTML tags and interact with API data are known as container component. This categorisation is basically separation of UI logic and application logic.

Component and its lifecycle 

In React JS, class-based components are extended from React.Component class which provides several lifecycle methods to component. render is also a life cycle method which must be implemented in React component. Other lifecycle methods are optional and can be used to gain more control over the React component. As ReactJS has evolved with time, few lifecycle methods are no longer supported and will be removed from library in coming update. In this article, we will look into the lifecycle methods which are supported by library version 16.4+.  

React lifecycle

React lifecycle: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/ 

To understand component's lifecycle methods and their invocation orders, we can divide all the methods in three broad category: Mounting, Updating, Unmounting 

  • Mounting: When component mounts then first of all constructor method (if present) is called. constructor method takes props as argument and pass props to the constructor method of React.Component class. Refer the example of class based component above. then getDerivedStateFromPropsstatic method will be invoked. getDerivedStateFromPropstakes two argument - props and state and returnsan object to update the state or returnsnull to update nothing. This lifecycle method is used when the state is dependson props. After getDerivedStateFromPropsmethod, render method is being called which returns the JSX. After render, componentDidMount is called which is the last method in mounting phase. We normally put API calls in componentDidMount lifecycle method. To summaries the mounting of component:

  • constructor 

constructor(props) { 
super(props); 
// code here 
}
  • getDerivedState From Props 

static getDerivedStateFromProps(props, state) { 
// code here 
// return updated state object or null 
} 
  • render 

render() { 
// code here 
} 
  • componentDidMount 

componentDidMount() { 
// code here 
} 
  • Updating:  After a component is mounted, A React component is changed either when the state of component or props passed is changed. on update, first getDerivedStateFromPropsstatic method is called which returns the object to update the state or return null to update nothing. Then shouldComponentUpdate lifecycle method is called which takes two arguments (nextProps and nextState) and return a boolean. This method decides whether render method should be invoked or not. If this method returnstrue then render method will be invoked otherwise component will not get updated. This method is used to optimise the React component by reducing the number of re-renders. if shouldComponentUpdate return true (which is also the default return value of method) then render method will be invoked which updated the component based on updated state or new props. After render method getSnapshotBeforeUpdate method is called. this method is invoked right before the rendered output is committed to DOM. It takes two arguments prevProps and prevState. this method gives access to DOM before React is going to update it with recent changes. For example, you can access last scroll position before update (re-render). Value returned by getSnapshotBeforeUpdate will be passed to componentDidUpdate method which is the next lifecycle method invoked. componentDidUpdate is called right after update occurs. This method takes three arguments prevProps, prevState and snapshot. last argument snapshot will be the value returned from getSnapshotBeforeUpdate lifecycle method. To summarise update phase of component:
  • getDerivedState From Props 

static getDerivedStateFromProps(props, state) { 
// code here 
// returns updated state object or null 
} 
  • should Component Update 

shouldComponentUpdate(prevPropsprevState) { 
// code here 
// returns true to re-render the component otherwise return false.  
// default is true 
} 
  • render 

render() { 
// code here 
} 
  • getSnapshot Before Update 

getSnapshotBeforeUpdate(prevPropsprevState) { 
// code here 
} 
  • component Did Update 

componentDidUpdate(prevPropspreState, snapshot) { 
// code here 
} 
  • Unmounting: Last phase of React component is unmount. it invokes the last method of React component's lifecycle componentWillUnmount. this method is called before the component is unmounted and destroyed. Normally, clean up code is put in componentWillUnmount method. we should not call setState method here as component is never going to be re-rendered after unmount. To summarise:

componentWillUnmount 
componentWillUnmount() { 
// code here 
}

Set up a React project 

As JavaScript has evolved and tooling has become an essential part of web development. There are many approaches to start a React project but the most popular one is create-react-app (popularly known as CRA). create-react-app is available as NPM module which means to use CRA, one must have NodeJS and NPM installed on machine. 

Create React project with CRA 

First check the NodeJS and NPM installation on machine by executing following command: 

node --version 
npm --version 
npx –version 

In case NodeJS is not install then download and install it from https://nodejs.org/en/. 

Once it is confirmed that NodeJS and NPM is installed on system then execute following command to create a React project: 

npx create-react-app My First React Project 

NPX command comes with NPM. It is used to use any NPM without actually installing the NPM. above command will create a new React project with latest version of create-react-app in your current directory. Execute following command to run the project: 

cd My First React Project 

npm start 

This would start a local server at port number 3000 and open default React page in browser.

React page in browser

Understanding project generated by CRA project generated by CRA

Above image shows the files and folder generated by CRA. let us go through it and understand: 

  • package.json: This file contains NPM dependencies, NPM scripts, project name, version etc... 
  • public folder: All public assets will be present in public folder like index.html, image or logo etc... 
  • src folder: All our JS code including React components will be present in src folder. 

CRA configured our React project with all the needed tooling required for web development. It configured Webpackdev server with hot reload ( on file save browser reloads the page to reflect latest change), Eslintreact-testing-library for unit testing React components etc... 

src/index.js is the starting point of our React project. Project also has one sample React component App.js. You can make changes to App.js and it will be reflected on browser. 

What type of React Component should I build in 2020 

So far, we have learnt different ways of writing React component. Now it is time to choose which pattern should you choose for writing React components. As we have discussed in previous article that ReactJS is moving towards functional programming paradigm and with the introduction of hooks in version 16.8, Writing functional component fulfils most of our use cases.

Let's create our first stateful functional component. We will be building a simple counter component. The final output looks like this: 

Counter component code: 

import React, { useState } from "react"; 
import "./Counter.css"; 
function Counter() { 
const [count, setCount] = useState(0); 
const increment = () => { 
const updatedCount = count + 1; 
setCount(updatedCount); 
}; 
const decrement = () => { 
const updatedCount = count - 1; 
setCount(updatedCount); 
}; 
return ( 
<div className="counterContainer"> 
<button type="button" onClick={decrement}> 
-
</button> 
<span>{count}</span> 
<button type="button" onClick={increment}> 
+ 
</button> 
</div> 
); 
} 

export default Counter; 

Styles are added in Counter.css 

.counterContainer { 
background-color: #fff; 
font-size: 24px; 
font-weight: 500; 
border: 1px solid #0874ce; 
border-radius: 3px; 
box-shadow: 1px 1px 4px 0 #0084ff; 
} 
.counterContainer button { 
outline: none; 
border: none; 
width: 50px; 
height: 40px; 
background-color: transparent; 
font-size: 24px; 
font-weight: 500; 
cursor: pointer; 
} 
.counterContainer span { 
color: #0084ff; 
} 

We have created a fully functional counter component which can be used anywhere in React application.

Pavan

Pavan kumar

JR TESTER

Doing service to Knowledgehut Solutions Pvt l.td as junior test engineer.


Website : http://www.pavantesting.com

Join the Discussion

Your email address will not be published. Required fields are marked *

Suggested Blogs

Easier Angular JS Routing With Angular UI Router

Takeaways from this article In this post, we will understand how and why Angular JS Routing is better in comparison to traditional frameworks, and how this routing can be achieved seamlessly with the help of Angular UI Router.  We will understand the usage and importance of states, and how they help in navigating easily through the application. We will see a sample with a state definition and its usage, and how it helps in resolving issues and making the page user-friendly.  Introduction  Angular JS is a popular application framework that is used for front-end development. It works great when creating single page applications. It is written in JavaScript and is being maintained by tech-giant Google. It is used to interpret the HTML attributes in a webpage in the form of directives and bind the respective input and output components of the model, that are represented in the form of JavaScript variables. Angular UI Routing helps navigate between views and pages seamlessly without getting messy, and in a user-friendly manner.  Note: It is assumed that the reader is aware of technologies like HTML, CSS, JavaScript and Angular JS. Native Angular Routing doesn’t have the following facilities: No nested views No named views Data can’t be passed around between two views The syntax of the route should be literally remembered to navigate the page The URL string has to be manually changed via the code base when a URL is changed. When a URL changes, all the links associated with that URL have to be changed and updated to point to the new location.  In order to minimize the above disadvantages, Angular UI Router is used.  Introduction to Angular JS Routing Angular JS Routing is an advanced technique that helps in routing, that has a declarative approach in navigating through the pages of a website. In a webpage, when a link that points to a different page is created, the URL has to be explicitly defined. This path has to be literally memorized and if it is changed, then the URL would have to be changed in all places where it was previously referenced. This is when Angular JS Routing comes into play.  Angular UI Router is a module in Angular JS that helps in the process of routing in Angular JS applications. The Router facilitates in the creation as well as usage of such routes in applications. The Router consists of a method called ‘stateProvider’ which helps in the creation of ‘states’, also known as ‘routes’.  The method ‘stateProvider’ takes the name of the state and the configurations of the state as its parameters. It looks like below:$stateProvider.state(stateName, stateConfig)The above function creates a state in the application. The parameter ‘stateName’ is a string value that is used to create a parent or a child state. To create a child state, the parent state is referenced with the help of the dot operator.  The ‘stateConfig’ parameter is an object that can take many properties, such as: template: It is a string in the form of HTML content or a function that returns a HTML string as the output.  templateUrl: It is a string that is a URL path to a specific template file or a function that returns a URL path string as the output.  templateProvider: It is a function that returns the HTML content as a string output.  Note: The ‘stateConfig’ parameter can take only one property at a time per state or per view with respect to the application.  The states in an application help the user in navigating or reconstituting to the situation that occurs within the application’s working. Note: The latest version of UI Router can be downloaded from the GitHub repository. Below are three examples when ‘stateConfig’ has different properties: With ‘template’ as a property: $stateProvider.state(‘stateName’,   {      url: ‘url for the specific state’,     template: ‘html content’,     controller: "name of controller for specific state" });With ‘templateUrl’ as a property:$stateProvider.state('stateName',   {     url: ‘url for the specific state’,     templateProvider: ‘function name’,     controller: "name of controller for specific state" });Introduction to Angular JS Router It is one of the modules in Angular JS that helps in creating routes for applications that use Angular JS.  Applications are encompassed in a shell, and this shell behaves like a placeholder for the dynamic content that would be generated later.  The UI Router is a routing framework that changes the views of the application based on not just the URL, but the state of the application as well.  It helps in bridging the gap between the traditional frameworks, by allowing nested views, named views, passage of data between two different views, and so on.  Routes are an integral part of Single Page Applications that are preferably created using Angular JS.  With the help of Angular UI Router, these routes can be created with ease and can be used with ease in Angular JS.  The ‘state’ facility gives the flexibility to encapsulate the location of the URL state name, special data for view, generate a view, or even locate a view.  Angular UI Router consists of a ‘stateProvider’ method that can be used to create a route or a state in an application.  The ‘stateProvider’ function takes the name of the state and the configurations of the state as its parameter.  In addition to this, Angular UI Router also helps resolve dependencies before initializing the controller.  It provides utility filters, declarative transitions, state change events, and so on.  What is the difference between State and URL Routes? State Route The views and routes of the Angular JS page will not be bound with just the URL of the site. The specific parts of the site can be changed with the help of UI Routing even if the URL has been kept the same. All the states, routing, and viewing capabilities of the page are handled at a single one-stop place- the ‘.config()’. URL Route URL route is a little different. It is usually implemented using ‘ngroute’, and it needs the implementation of methods such as ‘nginclude’. If the number of methods increases, the situation could get complicated and handling of these methods gets difficult.Stepwise routing with detailed explanation The node.js and npm have to be installed prior to working with the below steps.   For this purpose, the http-server node module has to be run and installed which will help in hosting the demo application that we would create.   It can be installed with the help of the below command: npm install http-server –gA hierarchical directory structure needs to be created. A sample has been shown below:Demo_App --app.js --index.html --nav.htmlThe ‘nav.html’ file needs to have the content as mentioned below: The nav bar title The contents of the file  The two different actions that would be created will also be mentioned here (The home page and the log in.) The index.html file will have the required dependencies along with nav.html file.  The nav.html file will be included in the body tag of the index.html page. The dependencies will be included with the help of ‘CDN’ in the head tag. A separate body tag will be used to define the ui-view div. The ui-view is a section where the information about various routes content and how they would be rendered is present.  The ui-view is a directive that is present inside the ui.router module.  The ui-view directive tells the ‘$state’ about the positioning of the template properties (or other property) It would look like below (sample):  An app.js file can be created, which is an application file that contains the route information and the actions that need to be performed with the help of the controller in the application framework. Below is a sample app.js file:var app = angular.module('Demo_App', [ "ui.router" ]);   app.config(function($stateProvider, $locationProvider,                                   $urlRouterProvider)   {       $stateProvider.state('home_page',   {               url : '/home',               template : "Home page",               controller : "hmeCtrl"         })           .state('login_page',   {               url : '/login',               template : "Login page",               controller : "lgnCtrl"         })       $urlRouterProvider.otherwise("/home");   });   app.controller('mainCtrl', function() {});   app.controller('hmeCtrl', function() {});   app.controller('lgnCtrl', function() {});The first line of the sample code declares the name of the application module and injects a ui.router module dependency into it. Next, the route configurations are defined inside the app.config and the dependency injections are set up.  The routes for the required attributes are set up with the help of the ‘stateProvider’ function and mentioning the required parameters.  Once the home page and the login have been set up, a condition is set up where the page would be redirected back to the home page if any of the routes don’t match the url name. This is done with the help of the ‘otherwise’ function.   Empty states are created for the controllers. This is done since it is a sample and no operation is being performed inside these states.  The above sample application can be run in the browser after the http-serve node module has been installed (as mentioned in the first step of this explanation).   Next step is to navigate to the ‘routingDemo’ folder and execute the below mentioned command:http-serverThis command helps in hosting the demonstration application on the default port that is 8080. This can be accessed with the help of the below mentioned link:localhost:8080/When the application is accessed via a browser, it will be a web application with two routes, namely: Home Login Conclusion In this post, we understood the prominence of Angular JS Routing and Router, and how they are different from the traditional approaches. They help bridge a gap between the features that traditional approaches implement, thereby increasing the ability of web pages to work and perform in a better, more user-friendly manner.
Rated 4.0/5 based on 14 customer reviews
6550
Easier Angular JS Routing With Angular UI Router

Takeaways from this article In this post, we will... Read More

Why You Should Use Angular JS

Takeaways from this articleIn this post, we will understand the prominence of Angular JS and how it plays an important role in front-end web development.  We will understand the applications of Angular JS, along with its usage.  We will also see how it works in comparison to other frameworks that are used for the same purpose.  What is Angular JS Angular JS is a JavaScript framework, that is currently being maintained by tech giant Google. It is used to build single page applications and web-based mobile applications that have interactivity with the users. It is simply an extension of the DOM model, making the application more user-friendly and robust. It is also an MVC framework implementation.  What are the applications of Angular JS? Menu creation Menu is trivial in almost all websites, be it single page, or multi-page. A menu is a navigation tool that responds to an input sent by a user- this could be a click, or a touch. It includes designs to make the web page more visible, or to make the user-experience better. Angular JS can be used to improve the user friendliness of the application. Elements from CSS can be added to the already present HTML (in the AngularJS framework) to improve the overall view of the page, thereby improving the user experience.  Interactive single page application There are various advantages when using a web page that behaves like a single page application. Instead of having to load and fetch separate pages from the memory as and when requested by the user every time they visit the site, a single page website would mean less overload on the memory and improved quality of user-experience. This is because all the code required by the web application can be retrieved in one go or can be dynamically loaded as and when required by the user. This behaves more like a desktop application, rather than like a multi-page application on the website.  10 advantages of Angular JS with respect to its peers Easy to implement MVC framework Many applications implement MVC frameworks, and Angular JS is one of them. The highlight of using Angular JS is the fact that MVC is implemented by splitting up the web application into various parts of MVC wherein every part will automatically perform its own remaining work. The MVC elements are managed by Angular JS without explicitly specifying so, and this acts as a pipeline that integrates them into separate elements. It is an intermediate point of contact that makes sure that the components fit and integrate properly. This way, the developer can concentrate on building quality applications without worrying about integration.  Interactive user interface Angular JS uses HTML to define the user-interface of the mobile application, and since HTML is simple to use, easy to understand and a declarative language, the entire application is simple. It is easier to use HTML than JavaScript to define the elements of the interface.  HTML is recognizable the moment it is encountered due to its format, tags, etc, in comparison to understanding that the language that has been used to implement the interface is JavaScript. In addition to this, HTML can be used to understand the flow of control of the application (HTML can be used with controllers in the MVC framework as well). Easy to understand directives A directive is a concept that can be used to work with Angular JS with the aim of embedding additional functionality into HTML, without making it more complicated. A limitless number of elements can be added to HTML, to improve the functionality of the application, without making it messy or complicated or difficult to maintain.  Angular JS facilitates directives that help the developer in building customized HTML tags. They can be identified with the help of their prefit ‘ng’. These newly built customized tags can be used as customized widgets. In addition to this, they can be used to manipulate the attributes of the DOM. There are certain default directives as well. The application maps the newly customized/default directives (which are also known as special attributes) to the elements of HTML so that it will generate the respective functionality for the application. This is achieved after creating the directives (customized or default attributes/HTML tags) and attaching that specific attribute/tag to the DOM element where it is required. With the help of data binding, changes to the application will be directly reflected in the ‘view’ section of the application.  Working with DOM is simple In general, the view part of MVC framework extends to the DOM in order to display the data, and at this point in time, the DOM is played with, in order to add extra functionality. The directives present in Angular JS can be used to bind the application data with the customized/default special attributes of HTML DOM elements. This means views are interpreted as HTML pages that come with placeholders which are later replaced with relevant values when dynamic data comes in, by Angular JS. This is a convenient way since it helps integrate the view with the website design. This will eliminate the complexity and messiness of the code.  POJO POJO simply means Plain Old JavaScript Object, which indicates that the Angular JS’s data models are simple, plain, easy to understand as well as implement. This also means that functions such as ‘getters’ and ‘setters’ are not required. The characteristics of the application can be changed directly. The presence of directives and DOM elements can be conveniently used to add the required functionalities.  Writing messy code is avoided The need to write too many lines of messy code can be avoided while using Angular JS. The need to write code for MVC pipeline is eliminated, thereby reducing considerable amount of overhead. The data model can be specified without the need to use other extra features or embedding other features. The concept of data binding makes sure that new data is not added into the view portion manually. It has to be integrated into the view with the help of DOM and directives. This way, the entire procedure is simple and easy.  Directives are different, and they are not a part of the code base of the application. This means a directive can be written in parallel without worrying about integrating it with other parts of the code, since this part will be taken care of by Angular JS itself. The time saved can be productively used to improve the quality and features of the Angular JS application instead of worrying about integrating the code with other parts of the application. As a result, there is more flexibility and the ability to extend the code when trying to build high-end web-based applications.  Filters in the data As the name suggests, it is a method that is used to filter the data before it reaches the view part of the application. It helps add filters such as formatting to decimal places, filtering an array based on a specific parameter, reversing the order of ranges, or implementing the concept of pagination for web pages in the application.  Filters can be created to make sure that the functions work properly and have been separated from the application. It also ensures that the functions are only associated with the data transformations with respect to the data and not the entire code of the application itself.  Communications know the context The Publisher-Subscriber system, which is also known as PubSub system is a common model that is used for a separate communication system. Most of the tools that implement Publisher-Subscriber model over the internet wouldn’t be aware of the context in which they are being used. But it is important to ensure that MVC elements that are not related to the same context are not placed together. When Angular JS is combined with Publisher Subscriber model, the context can be specifically mentioned, thereby addressing a specific part of the application. This ensures that the MVC part remains aloof. The remaining parts of the application won’t receive this context/message which means there won’t be any communication. This is easy to implement and simple to use with respect to communication that happens between controllers. Data binding is a technique that helps in the synchronization of the model and the view of the MVC framework. It helps to change, manipulate and work with the model and the view, and also changes their properties and data. With the help of data binding, any changes in the model would be directly reflected in the ‘view’ portion of the framework without the requirement to manipulate DOM or event handlers.  Service providers The scope of the code can be manipulated with the help of controllers in Angular JS. This means data can be placed prior to the code that would be used to implement the business logic or the server code. Controllers perform most of the heavy lifting, since Angular binds specific services to them. This way, the specific service of one controller wouldn’t get mixed with other parts of the application or with the MVC. An API is created to expose the functionality that needs to be used. The offline data can also be managed by synchronizing it with the server, and using various methods to pull or push data to and from a server. It can also be used to create a data sharing resource service that will ensure that different controllers share the same resources at that particular point in time.  Unit Testing capabilities  Angular JS was built by keeping the testing requirements in mind. This is because testing plays an important role, and can prove to be a significant step in identifying loopholes and issues. It also helps understand the overall application from a different perspective. For this change in perspective, end-to-end testing is performed on the Angular JS application. In Angular JS, unit testing can be performed with or without the help of Karma framework. Unit testing is usually performed separately on controllers and directives of Angular JS. The Angular JS application can also be tested by setting up individual test pages that would help create a specific component of the application, and then adding interactivity to it and checking if it works fine or not.  Dependency Injection (DI) The Angular JS application is bound with the help of Dependency Injection (DI). This is because Angular JS contains a built-in DI system. DI is basically a design pattern that discusses the components and their dependencies. DI helps the developers in creating components, working on their dependencies and facilitating the developers with the components that are required. It ensures that controllers are managed within their respective scopes easily. This is because the controllers depend on DI for data to be passed on to it. Why Angular JS should be used Angular JS is an open source framework that binds the data in two ways- the view and the model of the application are synchronized with each other when a user interaction takes place via the interface. This happens automatically so that the DOM gets updated accordingly. It is considered to be budget-friendly, and easy to create.  The highlight of using Angular JS is the fact that MVC is implemented by splitting up the application into parts of MVC that automatically perform the remaining work respectively. The MVC elements are managed by Angular JS without explicitly specifying, and acts as a pipeline that integrates their separate elements. It is an intermediate point of contact that makes sure that the components fit and integrate properly. Adding new functionalities isn’t a difficult task anymore; the view is not a part of DOM, which means new functions can be added and can be integrated with the application by making sure DOM interacts with the directive and the HTML page.  Conclusion In this post, we understood the significance of using AngularJS, how it can be applied in the real-world, and how it is advantageous in comparison to other frameworks with respect to its implementation, DOM model, simple coding capabilities, unit testing abilities and much more. Angular JS applications are simple to build, easy to use (user-friendly) as well as maintain. Since the amount of code that needs to be written is less, the developer can concentrate on building better and more interactive applications thereby improving consumer experience.  
Rated 4.0/5 based on 16 customer reviews
8470
Why You Should Use Angular JS

Takeaways from this articleIn this post, we will u... Read More

What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (Model View Whatever) framework backed by Google and is widely popular for creating dynamic apps. It offers a suite of tools that can be used for building the framework most suited to your single page application development. However, it can also be fully utilized to work for other categories of web pages. It works well with other web-based libraries and is fully extensible. All its features can be modified and even can be replaced to suit your unique development workflow and web feature needs.    As AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal  tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. AngularJS can be downloaded from https://angularjs.org/. If you’re new to AngularJS, it is better to get introductory information from http://angularjs.org. This site provides the basic information required to start working with AngularJS. It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Dependency Injection in the following section. IntroductionDependency Injection − AngularJS has a built-in dependency injection (DI) subsystem library whose work is to help the development team by making the application easier to develop, test, and understand. We will learn about each part of DI in detail. The topics we will go through in this article are: Dependency injection in AngularJS Value Injecting a Value Factory Injecting Values into a Factory Service Injecting Values into a Service Providers Configuring a Provider Constants Dependencies Between Modules Dependency injection in AngularJs Today’s software is totally designed in accordance with various design patterns. One such pattern is Dependency Injection. The DI design pattern specifies the pattern in which components are provided with their dependencies, instead of hard coding them within the component. AngularJS comes with a built-in dependency injection mechanism that enables you to divide your application into various types of components which can be injected into each other as their respective dependencies. Modularization of your application makes it easier to use, reuse, configure and even test the different components in your application. According to DI the core types of objects and components include the following: Value Factory Service Provider Constant These are the objects and components which can be injected into each other using AngularJS Dependency Injection. ValueFor AngularJS, the “Value” is a simple object. It can be a number, a string or a POJO (Plain old JavaScript object). This object is used to pass values in AngularJS factories, AngularJS services or AngularJS controllers during the run and config phase. The following example shows the steps involved in using a value. Step 1:  Define a module   var myMod = angular.module("myModule", []); Here, myModule is created using the AngularJS function angular.module(). You can add value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a value object and pass data to it.    myMod.value("numberValue", 10);    myMod.value("stringValue", "aaa");    myMod.value("objectValue", { field1 : 123, field2 : "abc"} );  Here, values are defined using the value () function on the module as created in step 1. The first parameter specifies the name of the value, and the second parameter is the value itself passed to other parts of the application. Factories, services and controllers can now reference these values by their value name. Step 3: Injecting a value in Controller function To inject a value into AngularJS controller function, we need to add a parameter with the same value name as that with which the value was defined. Note that the controller function is registered in angular via the angular.module(...).controller(...) function call. The $scope parameter passed to the controller function is the model for the controller. Thus, here myMod is the module registering the controller as myController, and $scope is the model for myController.  var myMod = angular.module("myModule", []);    myMod.value("numberValue", 10);    myMod.controller("myController", function($scope, numberValue) {     console.log(numberValue);    });Example: Using Value in AngularJS: Consider that you have already downloaded the latest AngularJS file from https://angularjs.org/ (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJs CDN for the same provided by Google.          Value in AngularJS             Value Example     The numberValue is: {{nValue}}        var myMod = angular.module('myModule', []);  myMod.value("numberValue", 5);  myMod.controller('myController', function($scope, numberValue)   {  $scope.nValue =numberValue;  });       Output: Factory In AngularJS, a factory is a function that is used to return a value. This function creates the value on demand whenever a service or controller needs any value injected from the factory. AngularJS applications normally use a factory function to calculate and return a value. The following example shows the steps involved in using a Factory. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a factory object and return data from it.    myMod.factory("myFactory", function() {        return "a value";    }); Here, we have used the factory function to create a Factory named myFactory. This Factory is returning “a value” from it. Step 3: Injecting values into factory Create a controller which gets the factory created value injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a factory value into AngularJS controller function, we need to add a parameter with the same value name as that with which the factory was defined.  var myMod = angular.module("myModule", []);    myMod.factory("myFactory", function() {        return "a value";    });  myMod.controller("MyController", function($scope, myFactory) {    console.log(myFactory);    }); Note: It is not the factory function that is injected, but the value produced by the factory function that gets injected. Example: Using Factory in AngularJS:         Factory                Factory Example    The numberFactory is: {{nFactory}}        var myMod = angular.module('myModule', []);  myMod.factory("myFactory", function() {    return "a value";    });        myMod.controller('myController', function($scope, myFactory) {  $scope. nFactory =myFactory;  });       Output: Service Web Services are helpful functions that perform a task. Similarly, in AngularJS, Service is a JavaScript object which contains a set of functions to perform certain tasks. Services are created by using service() function on a module and then injecting it into controllers. The following example shows the steps involved in using a Service. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service for defining the MathService for calculating basic math functions like add, subtract, multiply and divide. And then create another service, myService for defining a cube method to return the cube of a given number: myMod.service('MathService', function() {      this.add = function(a, b) { return a + b };      this.subtract = function(a, b) { return a - b };      this.multiply = function(a, b) { return a * b };      this.divide = function(a, b) { return a / b };  });  myMod.service('myService', function(MathService){       this.cube = function(a) {          return MathService.multiply(a,MathService.multiply(a,a));        }    }); The above code snippet uses MathService to call multiply function that takes two parameters and calculates the product.  Step 3: Inject the service "myService" into the controller   Create a controller which gets the Service injected (for explanation of Controller, go to the Value part of the article and navigate to its Step 3). To inject a Service function into AngularJS controller function, we need to add a parameter with the same value name as that with which the Service was defined.  myMod.controller('myController', function($scope, myService) {        $scope.doCube = function() {          $scope.result = myService.cube($scope.number);       }    }); Here we can even make it event based by adding an event in the main HTML content as:   Enter a number:            Cube      Result of Service: {{result}}      Example: Using Service in AngularJS:         Service Example           Service Example        Result of Service: {{result}}          var myMod = angular.module("myModule", []);  myMod.service('myService', function(){  this.sum = function(a,b) {  return a + b;  }      });  myMod.controller('myController', function($scope, myService) {  $scope.result = myService.sum (5, 6);  });       Output: Provider In AngularJS, a provider is used to internally create other values or services or factory during config phase (the phase during which AngularJS bootstraps itself). Provider can be considered to be the most flexible form of factory you can create. Provider is a special factory method with a get() function which is used to return the value or service or factory. The following example shows the steps involved in using a Provider. Step 1:  Define a module   var myMod = angular.module("myModule", []);   Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a service using provider which defines a method square to return the square of a number.  We use provider method to create a Provider.   myMod.config(function($provide) {       $provide.provider('myServiceProvider', function() {          this.$get = function() {             var factory = {};               factory.multiply = function(a, b) {                return a * b;              }             return factory;          };       });    });  Step 3: Inject the Provider "myServiceProvider" into the controller   Create a controller which gets the Provider injected (To understand how to create a Controller, go to the Value part of the article and navigate to its Step 3). To inject a Provider function into AngularJS controller function, we need to add a parameter with the same value name as that with which the provider was defined.  myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {        $scope.number = defaultInput;        $scope.result = myServiceProvider.multiply($scope.number, $scope.number);        $scope.square = function() {               $scope.result = myServiceProvider.multiply($scope.number, $scope.number);         }       });   Example: Using Provider in AngularJS:             Provider               Provider Example                        Enter a number:      X 2              Result: {{result}}                                  var myMod  = angular.module("myModule", []);              myMod.config(function($provide) {    $provide.provider('myServiceProvider', function() {    this.$get = function() {    var factory = {};    factory.multiply = function(a) {     return a * a;          }  return factory;      };        });      });             myMod.value("defaultInput", 10);             myMod.controller('myController', function($scope, myServiceProvider, defaultInput) {                $scope.number = defaultInput;                $scope.result = myServiceProvider.multiply($scope.number);    $scope.square = function() {    $scope.result = myServiceProvider.multiply($scope.number);     }        });               Output: Constants Config Phase of AngularJS has some restrictions for injected values, as you cannot inject values into the module.config() function. Instead constants are used to pass values at config phase. To define a constant value we use the constant() function of the defined module. Then for the constant parameter we provide a constant value. The following example shows the steps involved in using a Constant in AngularJS. Step 1: Define a module   var myMod = angular.module("myModule", []);  Here, myModule is created using the AngularJS function angular.module(). You can add Services, factory, value, controllers, directives, filters, and more, to your AngularJS application using a module. Step 2: Create a constant using the constant function and pass constant data to it.      myMod.constant("configParam", "constant value");    Example: Using Constant in AngularJS:              Constant            Constant Example      The numberConstant is:  {{nConstant}}            var myMod = angular.module('myModule', []);      myMod.constant("nConst", 5);      myMod.controller('myController', function($scope,nConst) {  $scope.nConstant =nConst;  });        Output: Difference between Constant and Value Values and Constants seem to be applied in the same way; however, Value differs from Constant in that value cannot be injected into configurations, but it can be intercepted by decorators. Also, a Constant can be used during the apps config phase, whereas a Value is only available during the run phase. The main difference between value and constant is that a value specified using Constant is available during the configuration phase while value specified using Value is available during the run phase. Example showing the difference between a Constant and a Value:          Constant                  Constant Example    {{ID}}          var myMod = angular.module('myModule', []);  myMod.value("myValue", "First Assignment");  myMod.value("myValue", "Second  Assignment");  myMod.constant("myConstant", "First Assignment");  myMod.constant("myConstant", "Second Assignment");  myMod.controller("myController", function($scope, myValue, myConstant) {  console.log("myValue: " + myValue);  console.log("myConstant: " + myConstant);  $scope.ID = " myValue: " + myValue + "&nbsp   myConstant: " + myConstant;  });       Output: Constant Example myValue: Second Assignment myConstant: First Assignment  Complete Example: AngularJS Dependency Injection Let's take an example to deploy all the above mentioned directives.                AngularJS Dependency Injection                 AngularJS Application Showing Dependency Injection         Enter a number:         X  2                Result: {{result}}                          var myMod = angular.module("myMod", []);    myMod.config(function($provide) {    $provide.provider('MathService', function() {    this.$get = function() {    var factory = {};    factory.multiply = function(a, b) {    return a * b;          }    return factory;      };        });      });    myMod.value("defaultInput", 10);    myMod.factory('MathService', function() {                var factory = {};                factory.multiply = function(a, b) {    return a * b;  }    return factory;  });           myMod.service('CalcService', function(MathService){    this.square = function(a) {    return MathService.multiply(a,a);     }         });    myMod.controller('myController', function($scope, CalcService, defaultInput) {    $scope.number = defaultInput;    $scope.result = CalcService.square($scope.number);    $scope.square = function() {    $scope.result = CalcService.square($scope.number);      }        });               Output: ConclusionIn the above article we learned about the Dependency Injection in AngularJS. Dependency Injection is a software design pattern that specifies how components get hold of their dependencies. In this pattern, components are given their dependencies instead of coding them directly within the component. We learned about core types of objects and components like Value, Factory, Service, Provider, and Constant. We learned how to create and register an injectable service and configure an injector with a service provider. We learned how to work with Injecting services to a controller. In the end we summarized with a complete example how Providers, Services, Factory and Value can be used.  
Rated 4.0/5 based on 14 customer reviews
6547
What Is Dependency Injection in AngularJS

AngularJS is an open source JavaScript MVW (M... Read More