Search

Featured blog posts

Top 21 Scrum Best Practices for Efficient Agile Workflow
  • by KnowledgeHut
  • 01 Apr 2019
  • Last updated on 09th Nov, 2021
  • 10 mins read

Scrum, arguably the most popular Agile framework in use across industries, has been proven to help develop products in a timely and highly efficient m... Read More

How to Become a Successful Full Stack Web Developer?

Full stack developer roles are among the hottest careers in the tech space now. These talented folks can develop a whole product from scratch. A ... Read More

LeSS Vs SAFe®️: Which Certification Should You Choose And Why?
  • by KnowledgeHut
  • 11 May 2018
  • Last updated on 26th Oct, 2021
  • 5 mins read

Agile and Scrum development is a trending technology in the IT industry. This approach delivers continuous iterations of a project on a timely basis.&... Read More

What is a Technical Project Manager?
  • by KnowledgeHut
  • 26 May 2021
  • Last updated on 17th Sep, 2021
  • 9 mins read

Many experienced professionals would like to start their career as a Technical Project Manager. This could be a wise decision,&nbs... Read More

How to Project Schedule in Project Management
  • by KnowledgeHut
  • 25 May 2021
  • Last updated on 17th Sep, 2021
  • 11 mins read

In project management, project scheduling encompasses listing activities, defining milestones and scheduling deliverables for delivery. This indicates... Read More

Best Project Management Certifications in 2021
  • by KnowledgeHut
  • 19 May 2020
  • Last updated on 17th Sep, 2021
  • 7 mins read

While nothing can replace industry work experience, there is no doubt that a credible certification can open up new opportunities and elevate your cur... Read More

Why Scrum Is Lightweight; Simple To Understand; Difficult To Master?
  • by KnowledgeHut
  • 06 Aug 2021
  • Last updated on 17th Sep, 2021
  • 9 mins read

85 percent of respondents say Scrum continues to improve quality of work life—State of Scrum 2017-2018 We have all heard companie... Read More

Scrum Master – The Scrum Team’s Servant-Leader!
  • by KnowledgeHut
  • 06 Aug 2021
  • Last updated on 17th Sep, 2021
  • 9 mins read

The term servant leader is synonymous with a Scrum Master. But what does it mean? The Scrum Master is a servant leader in Agile projects, but servant ... Read More

A Guide to Scaling Scrum
  • by KnowledgeHut
  • 06 Aug 2021
  • Last updated on 17th Sep, 2021
  • 8 mins read

Scrum has been proven to work well for small teams. But the true benefits of Agile can only be reaped if Agile and Scrum are scaled at the e... Read More

What Are Scrum Ceremonies – The 4 Agile Scrum Ceremonies Explained
  • by KnowledgeHut
  • 06 Aug 2021
  • Last updated on 17th Sep, 2021
  • 8 mins read

Scrum, one of the most popular Agile frameworks, works around short iterative release cycles called sprints. Each sprint is of a time-boxed duration d... Read More

Topics

Latest Posts

How To Use Mongodb Text Search?

MongoDB, one of the top NoSQL databases, is well renowned for its rapid speed, versatile structure, scalability, and excellent indexing capabilities. Before we get into the minutiae, let's look at the bigger picture. When it comes to locating content on the internet, full-text search is a must-have function. When we see the material utilizing the phrases or keywords, the best illustration is a Google search. In this post, we will learn about MongoDB's full-text search capabilities based on text indexes.MongoDB debuted with an experimental feature allowing Full-Text Search via Text Indexes in version 2.4. This feature is now an essential element of the product (and is no longer an experimental feature). In this post, we'll go through the fundamentals of MongoDB's full-text search capabilities.Searching Text - An essential featureConsider a normal Google search to better understand the concepts of full-text search. When we use Google to find content, we enter a string of text, strings, phrases, or keywords, and a number of results are returned. Full-text search in MongoDB enables you to run complicated queries comparable to those you'd run using a search engine. You can look for phrases and stemmed variations on a word, and you can also remove specific "negated" terms from your search results.You can create a text index on any field in the document whose value is a string or an array of strings using MongoDB full-text search. When we construct a text index on a field, MongoDB tokenizes and stems the text content of the indexed field and creates the indexes accordingly.Here are some other circumstances in which we might see a full-text search:Consider searching Wiki for your favorite topic. When you input a search term on Wiki, the search engine returns results for all articles that include the keywords/phrases you entered (even if those keywords were used deep inside the article). The relevancy of these search results is determined by their matched score. Consider a social networking site where a user may conduct a search to find all the posts that contain the term cats in them; or, to be more specific, all the posts that have comments that contain the word cats.Setting up for searchLet us now look at some practical examples to help us understand things better. I'd like you to follow along with me by running the examples in mongo shell. We'll start by creating some example data that we'll use throughout the tutorial, and then we'll go through key ideas.To begin, connect to your MongoDB server: Once you have MongoDB installed on your system, you can use mongo shell to connect with a MongoDB server.Run the mongo command from your command prompt to launch the MongoDB shell. The mongo command, by default, launches a shell linked to a locally installed MongoDB instance running on port 27017.Run the mongo command without any further parameters:>mongoThis will produce a welcome message with information about the server to which the shell is connected, as well as the version of MongoDB that is installed.Congrats, you are in mongo shell.Now run the following commands:>use messageLet's use the following statement to insert some documents.db.message.insert({"subject":"Ishan is having a dog", "content":"Dogs are most loyal pet", "likes": 60, "year":2015, "language":"english"}) db.message.insert({"subject":"Dogs eat cats", "content":"Cats are not evil", "likes": 30, "year":2015, "language":"english"}) db.message.insert({"subject":"Cats eat rats", "content":"Rats like cheese", "likes": 55, "year":2014, "language":"english"})Creating an IndexTo execute a text search, we must first establish a text index on the fields. This can be done on a single or numerous fields. The statement below will generate a text index on a single field.>db.message.createIndex({"subject":"text"})Let's use the following statement to insert some documents.db.message.insert({"subject":"Ishan is having a dog", "content":"Dogs are most loyal pet", "likes": 60, "year":2015, "language":"english"}) db.message.insert({"subject":"Dogs eat cats", "content":"Cats are not evil", "likes": 30, "year":2015, "language":"english"}) db.message.insert({"subject":"Cats eat rats", "content":"Rats like cheese", "likes": 55, "year":2014, "language":"english"})Creating an IndexTo execute a text search, we must first establish a text index on the fields. This can be done on a single or numerous fields. The statement below will generate a text index on a single field.>db.message.createIndex({"subject":"text"})We will generate a text index based on the description and subtitle attributes. In MongoDB, we can only construct one text index per collection. So, using the following line, we will establish a compound text index.db.messages.createIndex({"subject":"text","content":"text"})Using the $text operatorThe $text operator can also be used to search a text index. This operator is used to perform text search operations on a text-indexed collection. This operator tokenizes each search string with whitespace and treats most punctuation as delimiters with the exception of – and \." It performs a logical OR operation on the tokens after tokenizing the search phrase. Use the $meta query operator to sort the generated documents.Syntax:  $text:  { $search: , $language: , $caseSensitive: , $diacriticSensitive: }$search FieldWe'll now try to find documents with the keywords 'dog' in the topic and content boxes. We can use the following sentence to accomplish this.> db.message.find({$text: {$search: "dog"}})Example:> db.message.find({$text: {$search: "dog"}},{ subject: 1, content:1}) This will give the output as:   { "_id" : ObjectId("6176ce6de02fd70a168ad9c6"), "subject" : "Ishan is having a dog", "content" : "Dogs are most loyal pet" } { "_id" : ObjectId("6176ce77e02fd70a168ad9c7"), "subject" : "Dogs eat cats", "content" : "Cats are not evil" }Sorting documents based on search relevanceTextScoreEach page that has the search phrase in the indexed fields receives a score from the $text operator. The score shows a document's relevancy to a specific text search query. The score can be specified as part of the sort() method definition as well as the projection expression. The $meta: "textScore" expression offers information about the $text operation's processing. For more information on retrieving the score for projection or sort, see the $meta projection operator.We're doing a text search, thus we'd like to receive some statistics on how relevant the resulting documents are. To do this, we will use the $meta: "textScore" expression, which offers information about the $text operator's processing. Using the sort command, we will also sort the documents by textScore. A greater textScore indicates a better match.db.messages.find({$text: {$search: "dogs"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})This query returns the following documents:{ "_id" : ObjectId("6176b68b750fd1447889f942"), "subject" : "Joe owns a dog", "content" : "Dogs are man's best friend", "likes" : 60, "year" : 2015, "language" : "english", "score" : 1.2916666666666665 } { "_id" : ObjectId("6176b69f750fd1447889f943"), "subject" : "Dogs eat cats and dog eats pigeons too", "content" : "Cats are not evil", "likes" : 30, "year" : 2015, "language" : "english", "score" : 1 }As you can see, the first document gets a score of 1.2916666666666665 (since the keyword dog appears twice in its subject), whereas the second has a score of 1. The query also ordered the returned documents by their score in descending order.Compound Indexing:We will allow compound text indexing on the subject and content fields in our example. Proceed to run the following command in mongo shell:db.messages.createIndex({"subject":"text","content":"text"})This command will not work. Attempting to create a second text index will result in an error message stating that a full-text search index already exists. Why is this the case? The explanation is that text indexes are limited to one text index per collection. As a result, if you want to build another text index, you must delete the old one and establish a new one.db.messages.dropIndex("subject_text")   db.messages.createIndex({"subject":"text","content":"text"})After running the index creation queries listed above, try searching for all pages with the keyword cat.db.messages.find({$text: {$search: "cat"}}, {score: {$meta: "textScore"}}).sort({score:{$meta:"textScore"}})The above query will give the following output:{ "_id" : ObjectId("6176b69f750fd1447889f943"), "subject" : "Dogs eat cats and dog eats pigeons too", "content" : "Cats are not evil", "likes" : 30, "year" : 2015, "language" : "english", "score" : 1.3333333333333335 } { "_id" : ObjectId("6176b6cb750fd1447889f944"), "subject" : "Cats eat rats", "content" : "Rats do not cook food", "likes" : 55, "year" : 2014, "language" : "english", "score" : 0.6666666666666666 }Indexing the entire documentIn the last example, we created a composite index on the subject and content fields. However, there may be times when you want any text content in your papers to be searchable.Consider storing emails in MongoDB documents, for example. In the case of emails, all fields must be searchable, including Sender, Recipient, Subject, and Body. In such cases, you can use the $** wildcard specifier to index all of your document's string fields.The query would be as follows (make sure you delete the existing index before establishing a new one):db.messages.createIndex({"$**":"text"})This query would create text indexes on any string fields in our documents.Implementing text search in an aggregation pipeline:Text search is supported in the aggregate pipeline via the $text query operator in the $match stage. But the following regulations apply to text search in the aggregation pipeline:The pipeline's initial stage must be the $match stage with a $text. In the stage, a $text operator can only appear once. The $text operator expression is not permitted in $or or $not expressions. By default, the text search does not return matching documents in the order of matching scores. Use the $meta aggregation expression in the $sort stage to sort by descending score.The $text operator assigns a text score to each document that contains the search word in the index field. The score shows the importance of a document in relation to a given text search query.Examples: The following examples are based on a message collection with a text index on the field subject:>use people > db.people.insert({"name":"Ishan","pet":"dog"}) > db.people.insert({"name":"Abhresh","pet":"cat"}) > db.people.insert({"name":"Madan","pet":"cat"}) > db.people.insert({"name":"Sneha","pet":"dog"}) >db.people.find().pretty()Count the number of the document in which the pet value is dog:db.people.aggregate([{$match:{$text:{$search:"dog"}}},{$group:{_id:null,total:{$sum:1}}}])Count the number of the document in which the pet value is Cat:db.people.aggregate([{$match:{$text:{$search:"dog"}}},{$group:{_id:null,total:{$sum:1}}}])SummaryIf you handle string content in MongoDB, you should use full-text search to make your searches more effective and accurate. In this article, we demonstrated how to conduct a basic full-text search on a sample dataset. Full-text search has always been one of MongoDB's most requested capabilities. This article began with an introduction to full-text search before moving on to the fundamentals of generating text indexes. Following that, we looked into compound indexing, wildcard indexing. We also looked at some key concepts including analyzing text indexes, and text search in the aggregation pipeline. In the forthcoming MongoDB versions, we can expect some significant enhancements to this capability.
4786
How To Use Mongodb Text Search?

MongoDB, one of the top NoSQL databases, is well r... Read More

Installing and Managing Node.JS Using Node Version Manager (Nvm)

Node.js is the backbone of any modern project. It is not just another Backend technology, but also comes in-built with a package manager called npm. The npm package manager is required in all projects which need external node packages like ReactJS or Angular or Vue.Node.js is the second most popular backend technology after Java and is preferred by both start-ups and enterprises to build MERN(MongoDB, ExpressJS, ReactJS, NodeJS), MEAN(MongoDB, ExpressJS, Angular, NodeJS) or MEVN(MongoDB, ExpressJS, VueJS, NodeJS) stack projects. Companies like Netflix, NASA, Trello, PayPal, Uber, Yahoo use them for their large-scale projects. NodeJS is a completely open-source project, as the code is freely available on GitHub. It has a continually active development community. As it is been used in all top tech companies, so it is backed by funding and support from most of them.NodeJS has two ongoing releases, LTS and current, and, therefore two different versions. We will learn about them next.Understanding Node.js releasesIf we go to the NodeJS official site at https://nodejs.org/, we will see that there are two releases going on and they are LTS (Long Term Support) and Current. The LTS version currently is 14.18.1 and Current is 17.0.1.LTS is the stable version that goes through a lot of testing, and has a 30-month development cycle. Anything new that is added to this version will only be the bug fixes during this window. There will be no new features added to Node in this version. As per the NodeJS official site also, this version is recommended for most users. This is the version which is preferred by Enterprise users as they do not want to run into any issues in their large production projects.The other version is the Current version, which is a step ahead of the LTS version. In this version new features are added to the Node language. Sometimes these new features break a lot of things, but mostly they are newer features than those that are available in the LTS version. The current version is preferred by hobbyist programmers or small start-ups which want to work with innovative technologies.Node Version Manager (NVM)Node.js is an open-source project and there are times when we need one version over the other. Suppose we have a stable Production project, which is using the old LTS version. At the same time, we are working on a side-project, which needs the latest NodeJS Current version. In this case we must keep on deleting one Node version, working on the project, and returning to the other version for the other project.This is a very common problem and the best solution is to use nvm (Node.js Version Manager). It lets us switch between different versions of Node without much efforts. We will now understand through examples, how easy it is to switch, install and remove node versions on a system.Installing NVM on LinuxThe installation of nvm on Linux is mainly done through the command line. We are going to illustrate how to install nvm on Ubuntu, but you may note that a similar process can be followed for different flavours of Linux.I am using Ubuntu through WSL (Windows Subsystem for Linux), but the process is the same in an Ubuntu system also.Open the Ubuntu terminal and install wget through the package manager for Ubuntu known as ap-get. Through apt-get, we can easily install any package on an Ubuntu system.We are using the sudo apt-get install wget command. We have to use sudo because to install wget or any other packages, we need admin privileges. It might also ask for a password the first time and we have to give the admin or root password to proceed.Once wget is installed give the below command to install nvm on the Linux system.wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bashAfter the command is complete, we will get further commands to properly install nvm on our Linux system.We will run the given three commands separately from the terminal.Next, we will install a node.js version through nvm. Later on, we will see all the commands in more detail. We are using the command nvm install 14.8.1 to install a node version.Once it is installed, we can see the versions of node.js installed on our Ubuntu system by giving the nvm ls command.Installing NVM on macOSThe installation of nvm on mac is mainly done through command line and there are many different ways to do this. But we will follow the brew way, in which we install nvm through the macOS brew command.We need to install Homebrew first to proceed. It is an open-source manager for macOS, which makes it easier to install any software through the command line in macOS. The command to be given on a terminal is shown below. Also make sure that you are using the default bash shell, as this command will give an error in fish or csh shell./bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" It will also ask us for the root password.Once you give the root password the installation will start.There are two ways to install nvm, one is through wget and other is through curl. We need to install these through brew.We can install wget in our mac through the command brew install wget command.Once wget is installed give the below command to install nvm on the mac system.wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bashWe can also install curl through brew by giving the command brew install curl in the terminal.The command to install nvm through curl is below.curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bashBoth of these installs through wget or curl, will tell us to run the below command on a Mac to install nvm in our shell.So, we need to give these two commands from the terminal to install nvm properly on our mac system.The nvm commands to install and use it are the same on Ubuntu, mac and windows and we will see them in detail later. But we will install a version of node.js on mac to check if it is working properly. We are installing version 14.8.1 through the command nvm install 14.8.1 on our terminal.Now, if we do nvm ls on our terminal, we can see this version along with the other versions installed on our macos system.Installing NVM on WindowsThe installation process for Windows is totally different from MacOS. We will learn to do the same on Windows now, which requires the package nvm-windows. So, first go to https://github.com/coreybutler/nvm-windows/releases and click on nvm-setup.zip file.Once the zip file is downloaded, then extract it. It will be extracted as a single nvm-setup.exe file. Click on the same and the screen for Licence Agreement will appear, as below. But we will also be asked to trust this app in the Windows login screen.Click on “I accept the agreement” and then the Next button.It will give us a destination to install NVM, which we can keep as it is and click on the Next button.Next, it will ask us for the folder to create the Symlink, which we can keep and again click on the Next button.Finally, it will ask us to Install nvm and we can click the Install button now.This will install NVM on your machine. But if you have already installed a version of Node.JS prior to installing NVM, it will ask us for permission to control it. Click on Yes in the pop-up.After NVM is installed successfully, we will get the below screen. We now must click on the Finish button.To verify that the nvm was installed properly, run the command nvm –version from the Windows Terminal and we will get a long list of outputs showing that it was installed.Using NVMThere are various commands which we can use with nvm and change and install any version of node.js with ease. The commands are the same on Windows, MacOS or Linux. The first thing which we must do is to check the versions of node.js installed on the machine. We can do this by using the nvm ls command.As seen in the output, it gives us all the node versions installed on my machine.The most useful command is the nvm install command. Now, this can be used in two ways. We can use it as below –nvm install latest – To install the latest version of node.jsnvm install - To install any version of node.jsWe are using both commands to install the latest and a previous version of node.jsNow, running the nvs ls command will show all of the versions, available on the machine.To use a different version, we just have to use the nvm use command and give the version number. To use the version 17.0.1 in our case, we will give the command nvm use 17.0.1 in terminal. You might get an error like below if you are running this command as a non-admin user.To solve this issue, run the command prompt as an Administrator.Now, again use the nvm ls command and we will see that the 17.0.1 version is in use.We can also uninstall any version of node.js with the nvm uninstall command.SummaryThis article first introduced you to the different Node.JS versions and emphasized the importance of NVM. Next, you learnt how to install it on Ubuntu, then on MacOS and finally on Windows. Lastly, you have learnt about the different commands to install, use and check Node.JS versions. Good luck on your learning journey!
5448
Installing and Managing Node.JS Using Node Version...

Node.js is the backbone of any modern project. It ... Read More

What Are React Keys?

We Love Lists:In React, lists are in the form of arrays in JavaScript which can store multiple values of the same data type. The general need to render lists of items in applications, whether they are web or mobile apps, is because the lists help in displaying the data in the ordered format. This is also mostly used to display the menus on the websites. In other words, lists focus on the UI part of the website, and are mainly used in displaying the menus on a website. Some examples of lists in a website are the navbar menu, sidebar menu etc.In Normal JavaScriptIn the normal JavaScript, the map () function is used to transverse the lists. In the code given below, the map () function is used to take the array of numbers and then multiply the elements of an array with 3. Here we declare a new array variable tripled, assign the new array values that are returned by the map () function and then log it.Codeconst number = [2, 4, 5, 3];  const tripled = number.map((num) => num * 3);  console.log(tripled) Output : [6, 12, 15, 9]Lists in ReactWhile creating a list in React, the map() function is used to traverse the list elements and for updating the content in the lists. We use curly braces {} while working with lists in React.The output obtained through the map() function is assigned to the listItem. We specify the order nature of the list in the output and return a element for each item in the list. Finally, we render the React-DOM and obtain the result using the format at the end. Here’s what the code looks like:Index.jsimport React from 'react';      import ReactDOM from 'react-dom';      import reportWebVitals from './reportWebVitals';  // declaring the constants  const myList = [1, 2, 3, 4, 5];      const listItems = myList.map((myList)=>{      return {myList};      });      // rendering using the ReactDOM, render() function  ReactDOM.render(      {listItems} ,      document.getElementById('root')     );  reportWebVitals();OutputThe line ReactDom.render() method is used to render a React element into the DOM in the supplied container and returns a reference to the component. In this, we are importing any App.js file or any Index.html file for rendering the pages. In the above example we are declaring variables and using the function in the same file itself using the root element.Instead, we are using the “root” to point out the elements present in the index.ex.js file itself. The “root” element is the supplied container in DOM, and ListItem is the component. The root helps to auto render into the documents where it consists of Listelements to be printed out onto the console.How not to render ListIn the above example, we have initialized the list and rendered it using the map() function. We cannot render the list without using the “key” component. If we do so, we may get the output, but we may have some errors in the console. Consider the above example, which is coded without using the key component. In this case we have got the output, but the console has resulted in some warnings. So, it is suggested not to list the components in a program without the key component to uniquely identify the elements in the given list of elements.OutputWhat is the 'key' attribute?In React, keys are like a Special String attribute that is included in the Creation of List of Elements. Keys play a great significance in React, and they help us to know what are the items in the given list of elements that have changed or are updated or removed. In simple words, the keys help in providing the identity to the elements in the Lists. Keys help to uniquely identify the elements in the Lists.Syntax for Initialization of a KeyIn general, the keys are declared using a flower brace “{}”, and in the braces the corresponding functionality is added to get the output of the program. Keys should be given to the elements that are present inside the array, to provide a stable entity to the elements. To pick the right key from the list, the element should be uniquely identified among the elements in the list.Syntax: -   key = { }How should a key be chosen?It is recommended to choose a STRING as a key, that identifies the items uniquely in a given list. If the given list contains the variable values as strings, and those strings are said to be unique, then the corresponding values can be taken as a KEY. Else if the given list doesn’t contain Strings for variable values, the corresponding variable is type-casted explicitly to strings and then used in the program.By considering the problem encountered in the previous example, we try to remove the warnings using the Key attribute in the above program. After using the key attribute in the above example, we found there are no errors in the console, when we inspected the web page source. In this way the Key attribute is helpful to us in overcoming the errors in the creation of lists in React. The console is illustrated as below:Example of using keyLists.jsimport React from 'react'; // creating a function function Lists(){     const numbers = [1,2,3,4,5]     const listItems = numbers.map((number) =>  {number})     return {listItems} } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react'; // Defining the class named “App” class App extends React.Component {   render() {     return (               Usage of Keys resulted no Errors!                   )   } } export default App;OutputGenerally, the Key is used to identify the elements in a list uniquely. For the unique identification, we can use some alternatives like “id” or “index” forms as Keys from our data.Accessing Key element using ID formLists.jsimport React from 'react'; // Creating the function using function keyword in react function Lists(){     const stringLists = [ 'upgrad', 'knowledge', 'Hut', 'Blog', 'Writing'];         const updatedLists = stringLists.map((strList)=>             {strList} )           return {updatedLists}   } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react'; // the class Name is defined here “App” class App extends React.Component {   render() {     return (               Usage of ID Form                   )   } } export default App;OutputWhen we don’t have stable IDs for rendering of items, we use the item Index as the Key to access the elements in the list.Accessing Key Element using Index FormLists.jsLists.jsimport React from 'react'; // defining the function function Lists(){     const stringLists = [ 'bombay', 'delhi', 'calcutta' ];         const updatedLists = stringLists.map((strList, index)=>             {strList} )           return {updatedLists}   } export default Lists;App.jsimport './App.css'; import Lists from './Lists'; import React from 'react';  // class Name is defined here class App extends React.Component {   render() {     return (               Usage of INDEX Form                   )   } } export default App;OutputIt is not recommended to use the Indexes for the KEYS, if there is change in the order of items. That action sometimes may result in negative performance and could cause some issues with the Component State.Usage of Keys with ComponentKeys are generally used to identify the unique element in the given list of elements. But, the usage of keys while mapping to the elements describes a particular order. Assigning of keys creates an order and structure that leads to the correct implementation. For example, let us imagine we have created ListItem as a separate component and that ListItem is used for extraction of elements in the list of elements. In this case we should assign the Key component to the in the given array of elements but not to the component present in the ListItem itself.  Example of Incorrect Key usage with ComponentIndex.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function ListItem(props) {     const item = props.item;     return (       // Wrong Usage             {item}           );   }   function NameList(props) {     const myLists = props.myLists;     const listItems = myLists.map((strLists) =>       // Key should be used here         );   return (                 Incorrect Key Usage Example                 {listItems}           );   }   const myLists = ['csk', 'rcb', 'mi', 'srh', 'kkr', 'dd'];   ReactDOM.render(     ,     document.getElementById('root')   ) reportWebVitals();index.html         REACT TEST       OutputExample of Correct Key usage with Componentindex.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals'; function ListItem(props) {     const item = props.item;     return (       // key is not written here       {item}     );   }   function NameList(props) {     const myLists = props.myLists;     const listItems = myLists.map((strLists) =>       // Key is written here           );     return (                 Correct Key Usage Example               {listItems}           );   }    const myLists = ['HYD', 'MYS', 'AP', 'GOA'];    ReactDOM.render(     ,     document.getElementById('root')   ) reportWebVitals();index.html           REACT TEST         OutputWhile working with usage of Key with Component, we mostly work on two files namely the JavaScript file (“index.js”) and the HTML file (“index.html”). At this time, we don’t have any work to do with the App.js file, so we comment out the code lines in the file and work only on the index JavaScript and HTML files.The usage of keys in both the examples demonstrated above results in a similar output. But if there is any incorrect usage of keys, we come across errors in the corresponding HTML page on inspection. If the key is used correctly, there will not be any errors if we inspect the page.Keys Uniqueness among its SiblingsWe had learnt that the key should be unique among all the elements in the given list of elements i.e., it should be unique among the siblings in the given list. It is not compulsory that the keys initialized in the program should be Globally unique. We will try to produce two different arrays using the same set of keys as demonstrated below:Index.jsimport React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import reportWebVitals from './reportWebVitals';  function TourBlog(props) {     const place = (               {props.data.map((show) =>                       {show.title}                   )}           );     const famousfor = props.data.map((show) =>               {show.title}: {show.content}               );     return (               {place}                 {famousfor}           );   }   const data = [     {id: 1, title: 'Goa', content: 'Famous For Beaches.....!!'},     {id: 2, title: 'Mumbai', content: 'Famous For Street Food.........!!'},     {id: 3, title: 'Manali', content: 'Famous for Valleys & Beautiful Scenaries....!!'}   ];   ReactDOM.render(     ,     document.getElementById('root')   );   reportWebVitals();index.html           REACT TEST         OutputSummary To sum up what we have learnt in this article:A Key is a unique element among its siblings in the given list of elements.A Key is declared in array format. It takes the String format as a default state to bring the output from the list.If the given elements in the lists are not in the form of strings, they are type-casted into the string form and then accessed using the Key component in React.We can access the key elements using the Id and Index forms.We can use keys along with the Components. In this, we assign the Key component with the respective only, but not to the component unless the particular item type is not specified in the given program.Finally, we have seen the usage of Key component with two types of arrays in the given program itself to generate the result at the end.
5082
What Are React Keys?

We Love Lists:In React, lists are in the form of a... Read More