Search

Blogs blog posts

Add Voice to Your Blog With the SpeechSynthesis API

Voice-based technologies have become popular in recent years because of their several real-world applications. There are multiple organizations working on voice technologies, thanks to software like Google Assistant, Amazon Alexa, and Siri. Voice-based applications can completely change the way a user interacts with other software and hardware devices and improve the user experience. For web pages, users can listen to them instead of reading, alongside focusing on other important tasks.Voice technologies have played a very important role in making websites and blogs more accessible to people with disabilities and will continue to do so in the coming years. Let’s explore how we can add voice to a blog or a webpage.How can you make a web page talk or add voice to your blog? The Web Speech API can do that for you. It has two subsets – Speech Recognition API, which is used to recognize a voice, and Speech Synthesis API which is used to read something.Speech Synthesis API is a subset of Web Speech API and is a very popular way to add voice to a webpage or a blog. It enables developers to create natural human speech as playable audio. Arbitrary strings, words, and sentences can be converted into the sound of a person reciting the same things. Let’s learn a little more about Speech Synthesis API and then explore how you can implement it with your web page through an easy-to-follow tutorial.What is the Web Speech API?The Web Speech API was first introduced in 2012 and it is used by web developers to provide audio input and output features in web apps. The Web Speech API completely takes care of users’ privacy as it will not use the microphone and speaker services until the user grants permission for the same. And we do not need to add any third-party application for it. If the website is running on HTTPS protocol, then you need to permit it once otherwise, it will ask for permission in each new session. The web speech API also allows you to specify grammar objects and rules.The Web Speech API has two major applications:SpeechSynthesis: It is used in applications that need text-to-speech features and allows the web pages to read the content available on-page in human speech format. It uses the device's speech synthesizer for performing this.SpeechRecognition: It is used in applications that need voice recognition and transcribing. SpeechRecognition allows these applications to recognize a specific voice context by enabling the voice as an input and control method just like the keyboard and touch through the device microphone. With speech recognition, users can interact with websites and apps through voice commands easily.In this tutorial we are focusing on adding a voice to your blogs, we will explore the SpeechSynthesis API in more detail.Text to Speech with SpeechSynthesisSpeech Synthesis is a way of transforming text into voice through a computerized voice. In a simple form of output, the computer reads the typed text in a human-like voice.Now the question is how does Speech Synthesis work? The process of Speech Synthesis happens in three parts -Text to words:This pre-processing or normalization stage is focused on reducing the ambiguity in the text. It goes through the complete text and cleans it up so that the computer can read it without any mistakes.Reading a written paragraph may sound easy to you but it is a new thing for computers just like a young child. The written text can have multiple meanings, depending on the context. We can differentiate them using inflections in speech, but how would a computer differentiate? for example, 2001 can be a year or a lock combination or a measure of something. In human speech, the meaning will become clear based on the way we enunciate. This applies to date, time, special characters, abbreviations, acronyms, etc.Also, some words can have different meanings and they may sound the same, like- sell and cell. This stage of speech synthesis also handles Homographs.Words to Phonemes:Our API has figured out the words that need to be said and now it’s time to generate speech sounds to form those words. To pronounce a word, computers need a list of words mentioning their sound and how they are pronounced with the sound. Phonemes are ways of pronouncing a word or sequence of sound and basically, we will need a list of phonemes for each word and the computer will read everything. Again, it looks easy, but it is not a practical thing for computers. A single sentence can be read out in several ways depending on the context of talk and the meaning of the text. For example - ‘Read’ can be read as ‘red’, ‘read’ and ‘reed’, depending on the situation.To read out the words in the right manner they are broken down into their graphemes which are the written component unit, generally made from the syllables that make up a word. After that, phonemes are generated corresponding to them. It is like reading or trying to pronounce the words that you have encountered in the past.Phonemes to sound:As of now, the computer has cleaned the text and generated a list of phonemes for each word, and now it needs basic phonemes that the computer reads. So how do we get those phonemes? There are three approaches for that -1. Concatenative: This approach uses human voice recordings to generate phonemes. We record lots of human sound samples saying multiple things. These sentences are broken into words and then words are converted into phonemes. This method is limited to only one voice, and we need a lot of human efforts to perform this.  2. Formant: A speech can be considered as a pattern of sound that varies in volume, pitch, and frequency just like a musical instrument. Then it is possible to make a device that can generate these sound patterns. This way of generating phonemes is called Formant. Unlike Concatenative, Formant is an easier way of generating multiple voices but Concatenative sounds more natural than Formant.3. Articulatory:  The most realistic and complex approach of generating phonemes is Articulatory which is referred to as making computers speak by modeling a human vocal apparatus. The simplest explanation of Articulatory would be to build a talking robot with a mouth that produces sounds as humans with a combination of computer, electrical and mechanical components.Methods and properties of Speech Synthesis APISpeech Synthesis API inherits properties and methods from its parent interface, EventTarget. These properties, methods, and event handlers help developers to perform certain tasks and manage the speech synthesis while implementing the API. Some of these objects are:onstart: This event handler is fired when recognition service is started to listen the audio with intent to recognize the voice.onresult: This callback is fired when speech recognition returns a result.onerror: If an error occurs during recognition, this callback is fired.onend: This callback will run when the service is disconnected.SpeechSynthesis.cancel(): This method removes all the utterances from the utterance queue and the speaking will stop immediately.SpeechSynthesis.getVoices(): This method is used to display the list of all available voices in the current device.SpeechSynthesis.pause(): It puts the speechsynthesis object into paused mode or you can say it pauses the narration.SpeechSynthesis.resume(): If the Speechsynthesis object is in paused state then it will the narration.SpeechSynthesis.speak(): This method adds an utterance to the utterance queue that will be spoken.What are the benefits of using Speech Synthesizers?There are various useful applications of Speech Synthesizers and some of them are:It can help visually impaired people by reading books and web pages.In education, Speech Synthesizers can be used to teach spellings and pronunciations.It can also be used in the multimedia and telecommunication field to replace human efforts and reading emails and messages through the phone lines.Let your user engage with your application and device with the voice user interface.Personalize communication with users based on preference.Improve customer interaction with intelligent and natural responses.Adding Text-to-Speech to your website: Live Demo of Speech Synthesis APINow we will see how you can implement Speech Synthesis API in your web pages to let them talk with you.PrerequisitesA basic understanding of JavaScript and HTML.A Code Editor and browser, supporting Web Speech API, to view webpages.Browser CompatibilityThe Web Speech API has been in the market for a while, but it is not supported by every browser. You need to have a chrome version 33+ or an updated version of Safari.Let’s give a voice to our blog: Tutorial of Speech Synthesis API ImplementationLet’s start coding to implement Speech Synthesis API in our blog which is quite simple and can be done through a single line -SpeechSynthesis.speak(new SpeechSynthesisUtterance('Hey'))And we can also control the voice pitch, rate, and volume like this:const utterance = new SpeechSynthesisUtterance('Hey') utterance.pitch = 1.5 utterance.volume = 0.5 utterance.rate = 8 speechSynthesis.speak(utterance)In this tutorial, we will start from the basics, so it is easy for you to do it. First, we need to create a simple web page with some content on it and three buttons - Pause, Play, and Stop. We will also initiate a flag with the default value as false.<div>     <button id=play></button>     <button id=pause></button>     <button id=stop></button> </div> <article>     <h1>The Hare & the Tortoise</h1>     <p>A Hare was making fun of the Tortoise one day for being so slow.</p>     <p>"Do you ever get anywhere?" he asked with a mocking laugh. "Yes," replied the Tortoise</p>     <p>They both agreed on a race. </p>     <p>The Hare was soon far out of sight and to make the Tortoise feel how easy the race was for him, he lay down under a tree to take a nap. </p> <p>The Tortoise kept going slowly and steadily and passed the place where the Hare was sleeping to win the race.</p> <p>The Hare woke up and started running but it was already too late.</p>     <!-- More text... -->     <blockquote>Moral of the story...Slow and Steady wins the race.</blockquote> </article>You can also create a CSS file for the same to align buttons and other things.Now we need to ensure if the browser supports the Speech Synthesis API. If it is supported, we will create a reference for Speech Synthesis to assign synth variable. To check the compatibility with API, we will use the following code:onload = function() {   if ('speechSynthesis' in window) {       /* speech synthesis supported */   }      else { /* speech synthesis not supported */         msg = document.createElement('h5');         msg.textContent = "Detected no support for Speech Synthesis";         msg.style.textAlign = 'center';         msg.style.backgroundColor = 'red';         msg.style.color = 'white';         msg.style.marginTop = msg.style.marginBottom = 0;         document.body.insertBefore(msg, document.querySelector('div'));     } }Next for our three buttons, we will create respective functions with JavaScript - onClickPlay(), onClickPause(), and onClickStop(). Once the user clicks on one of them, the function will be called.if ('speechSynthesis' in window){     var synth = speechSynthesis;     var flag = false;     /* references to the buttons */     var playEle = document.querySelector('#play');     var pauseEle = document.querySelector('#pause');     var stopEle = document.querySelector('#stop');     Var flag = false;     /* click event handlers for the buttons */     playEle.addEventListener('click', onClickPlay);     pauseEle.addEventListener('click', onClickPause);     stopEle.addEventListener('click', onClickStop);     function onClickPlay() {     }     function onClickPause() {     }     function onClickStop() {     } }1. Play: Firstly, the flag is checked, when we click on the Play button; if it is set to false then we set it to true. The code in the first ‘if condition’ would not execute again until the flag is set to false.  We will create a new instance for SpeechSynthesisUtterance interface to hold information about narration language, voice pitch, volume, and narration speed.  SpeechSynthesis.getVoices() method is used to assign a voice to speak. There may be multiple voices available in your device’s software. It will return an array of all available voices in the device. The first voice is designated by utterance.voice = synth.getVoices()[0];Next, SpeechSynthesis.speak() is called to start the narration. The Article text is added as the parameter of the constructor and assigned to the utterance variable. SpeechSynthesis.paused is used to check if the narration is paused. If it is paused, then SpeechSynthesis.resume() method is used to resume it.  The onend is executed when the speech is finished to change the flag value to False again so that the speech execution can be started again when the button is clicked.function onClickPlay() {             if(!flag){                 flag = true;                 utterance = new SpeechSynthesisUtterance(document.querySelector('article').textContent);                 utterance.voice = getVoices()[0];                 utterance.onend = function(){                     flag = false; playEle.className = pauseEle.className = ''; stopEle.className = 'stopped';                 };                 playEle.className = 'played';                 stopEle.className = '';                 speak(utterance);             }              if (paused) { /* unpause/resume narration */                 playEle.className = 'played';                 pauseEle.className = '';                 resume();             }           }2. Pause: We will create onClickPause() function to check if narration is paused or running. If SpeechSynthesis.speaking and SpeechSynthesis.paused both statements are true, then onClickPause()  function pauses the speech with SpeechSynthesis.pause().function onClickPause() {             if(speaking && !paused){ /* pause narration */                 pauseEle.className = 'paused';                 playEle.className = '';                 pause();             }         }3. Stop: onClickStop is used to stop the narration if it is going on. It calls SpeechSynthesis.Cancel() to remove all utterances and stop the narration. function onClickStop() {             if(speaking){ /* stop narration */                 /* for safari */                 stopEle.className = 'stopped';                 playEle.className = pauseEle.className = '';                 flag = false;                 cancel();             }         } }The Scope of Web Speech APIWeb Speech API is very useful in various fields including education, data entry, Voice user interface control, increasing accessibility of web applications for people with disabilities, generally enhancing the user experience. In this tutorial, we explored how to add a voice to our blog and enable it to talk with the user using SpeechSynthesis API.As of now, Speech Synthesis API is only supported by a few browsers. We hope that soon, it will be supported by all the browsers and will have many other features. Also, as of now, the browser sends the text to the SpeechSynthesis API server for results. Working offline needs more consideration for odd situations.  It will be good to see the applications being controlled just by the voice.What is your experience of working with Web Speech? Where all do you see it being used? Share your experience and questions about using the Web Speech API with us.
Add Voice to Your Blog With the SpeechSynthesis API
KnowledgeHut

Add Voice to Your Blog With the SpeechSynthesis API

Voice-based technologies have become popular in recent years because of their several real-world applications. There are multiple organizations working on voice technologies, thanks to software like Google Assistant, Amazon Alexa, and Siri. Voice-based applications can completely change the way a user interacts with other software and hardware devices and improve the user experience. For web pages, users can listen to them instead of reading, alongside focusing on other important tasks.Voice technologies have played a very important role in making websites and blogs more accessible to people with disabilities and will continue to do so in the coming years. Let’s explore how we can add voice to a blog or a webpage.How can you make a web page talk or add voice to your blog? The Web Speech API can do that for you. It has two subsets – Speech Recognition API, which is used to recognize a voice, and Speech Synthesis API which is used to read something.Speech Synthesis API is a subset of Web Speech API and is a very popular way to add voice to a webpage or a blog. It enables developers to create natural human speech as playable audio. Arbitrary strings, words, and sentences can be converted into the sound of a person reciting the same things. Let’s learn a little more about Speech Synthesis API and then explore how you can implement it with your web page through an easy-to-follow tutorial.What is the Web Speech API?The Web Speech API was first introduced in 2012 and it is used by web developers to provide audio input and output features in web apps. The Web Speech API completely takes care of users’ privacy as it will not use the microphone and speaker services until the user grants permission for the same. And we do not need to add any third-party application for it. If the website is running on HTTPS protocol, then you need to permit it once otherwise, it will ask for permission in each new session. The web speech API also allows you to specify grammar objects and rules.The Web Speech API has two major applications:SpeechSynthesis: It is used in applications that need text-to-speech features and allows the web pages to read the content available on-page in human speech format. It uses the device's speech synthesizer for performing this.SpeechRecognition: It is used in applications that need voice recognition and transcribing. SpeechRecognition allows these applications to recognize a specific voice context by enabling the voice as an input and control method just like the keyboard and touch through the device microphone. With speech recognition, users can interact with websites and apps through voice commands easily.In this tutorial we are focusing on adding a voice to your blogs, we will explore the SpeechSynthesis API in more detail.Text to Speech with SpeechSynthesisSpeech Synthesis is a way of transforming text into voice through a computerized voice. In a simple form of output, the computer reads the typed text in a human-like voice.Now the question is how does Speech Synthesis work? The process of Speech Synthesis happens in three parts -Text to words:This pre-processing or normalization stage is focused on reducing the ambiguity in the text. It goes through the complete text and cleans it up so that the computer can read it without any mistakes.Reading a written paragraph may sound easy to you but it is a new thing for computers just like a young child. The written text can have multiple meanings, depending on the context. We can differentiate them using inflections in speech, but how would a computer differentiate? for example, 2001 can be a year or a lock combination or a measure of something. In human speech, the meaning will become clear based on the way we enunciate. This applies to date, time, special characters, abbreviations, acronyms, etc.Also, some words can have different meanings and they may sound the same, like- sell and cell. This stage of speech synthesis also handles Homographs.Words to Phonemes:Our API has figured out the words that need to be said and now it’s time to generate speech sounds to form those words. To pronounce a word, computers need a list of words mentioning their sound and how they are pronounced with the sound. Phonemes are ways of pronouncing a word or sequence of sound and basically, we will need a list of phonemes for each word and the computer will read everything. Again, it looks easy, but it is not a practical thing for computers. A single sentence can be read out in several ways depending on the context of talk and the meaning of the text. For example - ‘Read’ can be read as ‘red’, ‘read’ and ‘reed’, depending on the situation.To read out the words in the right manner they are broken down into their graphemes which are the written component unit, generally made from the syllables that make up a word. After that, phonemes are generated corresponding to them. It is like reading or trying to pronounce the words that you have encountered in the past.Phonemes to sound:As of now, the computer has cleaned the text and generated a list of phonemes for each word, and now it needs basic phonemes that the computer reads. So how do we get those phonemes? There are three approaches for that -1. Concatenative: This approach uses human voice recordings to generate phonemes. We record lots of human sound samples saying multiple things. These sentences are broken into words and then words are converted into phonemes. This method is limited to only one voice, and we need a lot of human efforts to perform this.  2. Formant: A speech can be considered as a pattern of sound that varies in volume, pitch, and frequency just like a musical instrument. Then it is possible to make a device that can generate these sound patterns. This way of generating phonemes is called Formant. Unlike Concatenative, Formant is an easier way of generating multiple voices but Concatenative sounds more natural than Formant.3. Articulatory:  The most realistic and complex approach of generating phonemes is Articulatory which is referred to as making computers speak by modeling a human vocal apparatus. The simplest explanation of Articulatory would be to build a talking robot with a mouth that produces sounds as humans with a combination of computer, electrical and mechanical components.Methods and properties of Speech Synthesis APISpeech Synthesis API inherits properties and methods from its parent interface, EventTarget. These properties, methods, and event handlers help developers to perform certain tasks and manage the speech synthesis while implementing the API. Some of these objects are:onstart: This event handler is fired when recognition service is started to listen the audio with intent to recognize the voice.onresult: This callback is fired when speech recognition returns a result.onerror: If an error occurs during recognition, this callback is fired.onend: This callback will run when the service is disconnected.SpeechSynthesis.cancel(): This method removes all the utterances from the utterance queue and the speaking will stop immediately.SpeechSynthesis.getVoices(): This method is used to display the list of all available voices in the current device.SpeechSynthesis.pause(): It puts the speechsynthesis object into paused mode or you can say it pauses the narration.SpeechSynthesis.resume(): If the Speechsynthesis object is in paused state then it will the narration.SpeechSynthesis.speak(): This method adds an utterance to the utterance queue that will be spoken.What are the benefits of using Speech Synthesizers?There are various useful applications of Speech Synthesizers and some of them are:It can help visually impaired people by reading books and web pages.In education, Speech Synthesizers can be used to teach spellings and pronunciations.It can also be used in the multimedia and telecommunication field to replace human efforts and reading emails and messages through the phone lines.Let your user engage with your application and device with the voice user interface.Personalize communication with users based on preference.Improve customer interaction with intelligent and natural responses.Adding Text-to-Speech to your website: Live Demo of Speech Synthesis APINow we will see how you can implement Speech Synthesis API in your web pages to let them talk with you.PrerequisitesA basic understanding of JavaScript and HTML.A Code Editor and browser, supporting Web Speech API, to view webpages.Browser CompatibilityThe Web Speech API has been in the market for a while, but it is not supported by every browser. You need to have a chrome version 33+ or an updated version of Safari.Let’s give a voice to our blog: Tutorial of Speech Synthesis API ImplementationLet’s start coding to implement Speech Synthesis API in our blog which is quite simple and can be done through a single line -SpeechSynthesis.speak(new SpeechSynthesisUtterance('Hey'))And we can also control the voice pitch, rate, and volume like this:const utterance = new SpeechSynthesisUtterance('Hey') utterance.pitch = 1.5 utterance.volume = 0.5 utterance.rate = 8 speechSynthesis.speak(utterance)In this tutorial, we will start from the basics, so it is easy for you to do it. First, we need to create a simple web page with some content on it and three buttons - Pause, Play, and Stop. We will also initiate a flag with the default value as false.                 The Hare & the Tortoise     A Hare was making fun of the Tortoise one day for being so slow.     "Do you ever get anywhere?" he asked with a mocking laugh. "Yes," replied the Tortoise     They both agreed on a race.     The Hare was soon far out of sight and to make the Tortoise feel how easy the race was for him, he lay down under a tree to take a nap. The Tortoise kept going slowly and steadily and passed the place where the Hare was sleeping to win the race. The Hare woke up and started running but it was already too late.         Moral of the story...Slow and Steady wins the race. You can also create a CSS file for the same to align buttons and other things.Now we need to ensure if the browser supports the Speech Synthesis API. If it is supported, we will create a reference for Speech Synthesis to assign synth variable. To check the compatibility with API, we will use the following code:onload = function() {   if ('speechSynthesis' in window) {       /* speech synthesis supported */   }      else { /* speech synthesis not supported */         msg = document.createElement('h5');         msg.textContent = "Detected no support for Speech Synthesis";         msg.style.textAlign = 'center';         msg.style.backgroundColor = 'red';         msg.style.color = 'white';         msg.style.marginTop = msg.style.marginBottom = 0;         document.body.insertBefore(msg, document.querySelector('div'));     } }Next for our three buttons, we will create respective functions with JavaScript - onClickPlay(), onClickPause(), and onClickStop(). Once the user clicks on one of them, the function will be called.if ('speechSynthesis' in window){     var synth = speechSynthesis;     var flag = false;     /* references to the buttons */     var playEle = document.querySelector('#play');     var pauseEle = document.querySelector('#pause');     var stopEle = document.querySelector('#stop');     Var flag = false;     /* click event handlers for the buttons */     playEle.addEventListener('click', onClickPlay);     pauseEle.addEventListener('click', onClickPause);     stopEle.addEventListener('click', onClickStop);     function onClickPlay() {     }     function onClickPause() {     }     function onClickStop() {     } }1. Play: Firstly, the flag is checked, when we click on the Play button; if it is set to false then we set it to true. The code in the first ‘if condition’ would not execute again until the flag is set to false.  We will create a new instance for SpeechSynthesisUtterance interface to hold information about narration language, voice pitch, volume, and narration speed.  SpeechSynthesis.getVoices() method is used to assign a voice to speak. There may be multiple voices available in your device’s software. It will return an array of all available voices in the device. The first voice is designated by utterance.voice = synth.getVoices()[0];Next, SpeechSynthesis.speak() is called to start the narration. The Article text is added as the parameter of the constructor and assigned to the utterance variable. SpeechSynthesis.paused is used to check if the narration is paused. If it is paused, then SpeechSynthesis.resume() method is used to resume it.  The onend is executed when the speech is finished to change the flag value to False again so that the speech execution can be started again when the button is clicked.function onClickPlay() {             if(!flag){                 flag = true;                 utterance = new SpeechSynthesisUtterance(document.querySelector('article').textContent);                 utterance.voice = getVoices()[0];                 utterance.onend = function(){                     flag = false; playEle.className = pauseEle.className = ''; stopEle.className = 'stopped';                 };                 playEle.className = 'played';                 stopEle.className = '';                 speak(utterance);             }              if (paused) { /* unpause/resume narration */                 playEle.className = 'played';                 pauseEle.className = '';                 resume();             }           }2. Pause: We will create onClickPause() function to check if narration is paused or running. If SpeechSynthesis.speaking and SpeechSynthesis.paused both statements are true, then onClickPause()  function pauses the speech with SpeechSynthesis.pause().function onClickPause() {             if(speaking && !paused){ /* pause narration */                 pauseEle.className = 'paused';                 playEle.className = '';                 pause();             }         }3. Stop: onClickStop is used to stop the narration if it is going on. It calls SpeechSynthesis.Cancel() to remove all utterances and stop the narration. function onClickStop() {             if(speaking){ /* stop narration */                 /* for safari */                 stopEle.className = 'stopped';                 playEle.className = pauseEle.className = '';                 flag = false;                 cancel();             }         } }The Scope of Web Speech APIWeb Speech API is very useful in various fields including education, data entry, Voice user interface control, increasing accessibility of web applications for people with disabilities, generally enhancing the user experience. In this tutorial, we explored how to add a voice to our blog and enable it to talk with the user using SpeechSynthesis API.As of now, Speech Synthesis API is only supported by a few browsers. We hope that soon, it will be supported by all the browsers and will have many other features. Also, as of now, the browser sends the text to the SpeechSynthesis API server for results. Working offline needs more consideration for odd situations.  It will be good to see the applications being controlled just by the voice.What is your experience of working with Web Speech? Where all do you see it being used? Share your experience and questions about using the Web Speech API with us.
3629
Add Voice to Your Blog With the SpeechSynthesis AP...

Voice-based technologies have become popular in re... Read More

Build Beautiful UI With Tailwind CSS Templates

Chapter 1Tailwind CSS TemplatesSince 2017, Tailwind CSS has gained a lot of traction among developers because it allows them to create bespoke interfaces without being constrained by any user interface kit standards. It offers outstanding advantages for web design.Tailwind CSS also possesses a default setting that can be bypassed using a tailwind.config.js file. This allows users and web developers to customize their projects easily using a variety of styling, themes, spacing, and palette options. Tailwind's features enable seamless project management and website development to user satisfaction.Build beautiful UI with Tailwind CSS TemplatesCSS—an acronym for Cascading Style Sheets, is a programming language used in styling HTML documents. HTML stands for HyperText Makeup Language. While HTML may sound like a programming language, it is a web document and not a programming language.These web documents are written with HTML code that uses tags and specific keywords that could be read and displayed correctly by the applications specifically designed for this purpose —web browsers. Using CSS, a single HTML page can be styled with multiple layouts and designs called stylesheets, with these external stylesheets being stored on CSS files.Common CSS WorkflowsMany CSS frameworks, such as BootStrap, Bulma, Foundation, etc., are utilized to streamline how these HTML documents are styled and build responsive layouts for these documents. These CSS frameworks are templates with already-made, multiple style sheets that make it easier for the web developer or designer to set up web pages while saving them the stress of intensive CSS code writing to complete specific tasks.Naturally, with these ready-to-use style sheets, CSS frameworks make web development faster, easier, and more convenient. Still, most of these CSS frameworks have limitations and rules that streamline styling, allow for the building of responsive page layouts, and restrict designer creativity simultaneously.In crafting a design system, it is prudent to allow the savvy web designer to curate a variety of design systems that can be leveraged to create a user-friendly interface that will improve usability and overall user interaction. However, this fluidity is usually restricted.CSS frameworks like BootStrap make use of row elements that contain horizontally placed columns that can be only limited to twelve (12). This framework also classifies device sizes into xs, sm, md, and lg, which helps it develop a user interface with exceptional pixels across various devices of various sizes.Since the Bootstrap grid is divided into twelve (12) columns, layouts that do not add to this number are hard to materialize. Also, since CSS files contain external style sheets that help the page layout and design, with Bootstrap, these style sheets supporting files need to be separately downloaded, resulting in a slower loading speed of web pages.This table illustrates how the Bootstrap grid system works across multiple devices.Bulma is another CSS framework that relies on Flexbox. Open-sourced, this responsive CSS framework utilizes a variety of in-built characteristics which help reduce intensive CSS coding. Bulma has impressive page layouts which are smooth and allow users to select only needed elements, making the entire process even easier.However, with a relatively smaller community, many features and tools such as plug-ins and theming are not available on Bulma. Also, elements such as page header, list group, and wells are not available on Bulma, which significantly limits the creation of design systems and flexibility. There are also compatibility issues experienced with Internet Explorer, and this is a significant dent in cross-platform compatibility for Bulma.The Solution - Introducing Tailwind CSSTailwind CSS is a truly utility-first CSS framework. Easy to customize, impressive cross-platform compatibility with a tiny build size, Tailwind allows users to build anything literally. This CSS has a unique set of customized defaults that are impressively customizable.Tailwind uses the latest and best CSS features with modern characteristics, giving the developer a delightful experience. The ready-to-use UI kits combined with their efficient utility improve designs and enable design systems to make Tailwind unmatched.What Tailwind Is NotA fantastic feature of this CSS framework is its unique qualities which separate it from conventional CSS frameworks like Bootstrap, Bulma, or Foundation. Tailwind does not have a default theme and is not a User Interface kit with imposed design decisions that limits creativity like Bootstrap.It also does not come with built-in user interface components, making it a fantastic Front-End Framework tool. Tailwind possesses a cross-section of pre-designed widgets with which you can build your site. It uses a variety of utility classes in creating a neat and clean UI that is unique and flexible.Quick Start with TailwindTailwind's ease-of-use can be utilized in making projects easier to build. A sign-up form can easily be created with Tailwind CSS using the following steps:Add tailwind.min.css file to your brand-new code pen by going to the CSS settings and loading up tailwind CSS. This eliminates the need for CSS or javascript.Using Emmet, a shorthand tool, set up a nice background with your desired plot shade. You'll notice that you don't have to force your project to have a width, and it's going to be automatically centered thanks to the flexbox classes.You can then start creating your sign-up form. Do all the HTML first, and then style it with your preferences. Input labels and boxes for required information on the sign-up form and add a checkbox where users can agree to terms and conditions.Work on styling, preferred fonts, sizes, colors, padding, margin, background, etc. This should be the bulk and final part of your entire project.Using the Tailwind CLITailwind uses purge to remove unused styles, and in production, it can end up being between 5 and 10 kilobytes which is small. But in development, CSS files can get big, especially if several things are added to the config file. Bearing in mind that the browser can handle is limited, Tailwind CLI avoids having to compile all the CSS upfront and instead compiles only the CSS being used as you need it.The easiest and quickest method to get up and running with Tailwind CSS from scratch is with the Tailwind CLI tool.1. Tailwind CSS InstallationInstall tailwindcss through npm, and create tailwind.config.js file as below2. Configure template pathsAdd the paths to all template files in tailwind.config.js file.3. Add the Tailwind directives to CSSAdd the @tailwind directives to the main CSS file for each Tailwind’s layers.4. Initiate the Tailwind CLI build processExecute the CLI tool to check template files for classes and build CSS.5. Commence using Tailwind in HTMLAdd compiled CSS file to the and use Tailwind’s utility classes to style the content.Chapter 2Turbocharge your React components with TailwindTo integrate Tailwind in a Create-React Project, first, you have to use NPX create to create a react app, and when successful, you will get a happy hacking message which means that the react app has been successfully created.#using NPXnpx create-react-app tailwindreactexample-appOpen the react app and open the package.json file, copy the npm command, paste it there, and run it. Then install craco to do the job because the react app does not have both the CSS by default. Since Create React App doesn’t override the PostCSS configuration by default, installing CRACO to configure Tailwind is necessary.npm install @craco/craco #using Yarn yarn add @craco/cracoOnce installed, change the three scripts, remove the react scripts into back-click code. Then proceed to create a craco.config.js file in the root of the directory. Next step is to configure the Tailwind CSS with a file called tailwind.config.js, which the npx will automatically create, and import the index CSS files from the source directory.#create a CRACO configuration file touch craco.config.js #creates a tailwind.config.js npx tailwindcss initIf done correctly, npm run start will automatically open the browser, and it will run out against CSS. Viola!ExampleNPMInstall Material Tailwind via NPMYarnInstall Material Tailwind via YarnImport Tailwind Style SheetImport file tailwind.css into your app.js file.Icons FontsLink could be added for material icons fonts inside the project's head. Use font awesome font family for the project add a link for it inside the head of your projectOutputThe Dark SideTo incorporate Dark Mode with Tailwind CSS, first, you will need to install Tailwind CSS and gatsby-plugin-post CSS. Ensure to include gatsby-config.js in the file as well. Then in a root directory, proceed to create a postcss.config.js file, then edit global styles.At this point, light and dark themes can be integrated into the file. Finally, Tailwind CSS Documentation will test out your newly integrated dark theme.Chapter 3Integrate Tailwinnnd CSS with AngularAnother critical feature of Tailwind CSS is its versatility and ability to be integrated on multiple platforms. One of which is Angular, a mobile and web app front-end development platform.Since 2009 when Misko Hebery and Adam Abrons developed its first framework, Angular has continued to evolve progressively, and its popularity and efficiency have made angular developers most sought after. Recently, its team launched version 11.2, which can now accept Tailwind CSS. Below is a guide on integrating this ease-of-use CSS into your angular projects.The first step is to make sure that your Angular is up to date with the latest version —Angular v11.2. Once this is done, proceed to install the TailwindCSS. You can either do this through yarn or npm. It is also necessary that you have the Tailwind CSS peer-dependencies installed—autoprefixer and postcss.Once installations are complete, you can generate the Tailwind CSS configuration file and then add the TailwindCSS styles in the Global Styles.css file. You can easily create a navigation menu when all of this is done.How to use Tailwind CSS in AngularStep 1: Generate Angular applicationCreate an Angular project utilizing the ng new command:Step 2: Install DependenciesInstall required dependencies via npm:Step 3: Create configuration fileThe above command would create the tailwind.config.js file containing your Tailwind CSS configuration.Step 4: Configure location of HTML (TypeScript files)Tailwind utility classes are generated on request. Replace the content on the tailwind.config.js file.The configuration informs Tailwind CSS that the HTML and TypeScript need to be scanned and are located inside the src and projects folders.Step 5: Add Tailwind directives to the global CSS file.Open your global CSS file (src/style.css) and add content below:Step 6: Start angular application by npm commandCongratulations, you have successfully integrated Tailwind CSS with Angular.Ready to use Tailwind CSS Components – Tailwind UITailwind Components is a community-contributed collection of over 800 Tailwind UI components and templates to launch landing pages, new apps, and projects quickly. Logins, inputs, selects, drop-downs, tabs, and modals are all constructed with Tailwind CSS, and there's even a handy cheat sheet included.This collection is open to users who want to provide helpful templates for other users and the community. These templates or components can easily be accessed by clicking on them. Users can preview, download, fork it into GitHub, or even copy the code when redirected to the individual page.Final WordsTailwind CSS utilizes PurgeCSS in reducing file size. This is done by scanning the HTML code to remove unused classes. When combined with Tailwind CSS, this is very beneficial.Heavy products are usually a characteristic of expanding projects, and this can be a real problem for web browsers causing slower page loading. PurgeCSS efficiently takes care of this, reducing the file size and making projects easily manageable.Finally, Tailwind CSS proves easier to create and develop custom components. The theme function can alternatively be used in deriving values instead of intensive coding. This way, users are able to reduce and possibly avoid altogether having to name several classes.Are you about to start a new front-end or full-stack project? Endeavor to use Tailwind CSS for that project to enjoy all of the benefits talked about in this article.
4800
Build Beautiful UI With Tailwind CSS Templates

Chapter 1Tailwind CSS TemplatesSince 2017, Tailwin... Read More

Migrating From jQuery to React? Here’s How!

jQuery isn’t React and React isn’t jQuery:We utilize jQuery to directly alter the Document Object Model (DOM) (i.e. add/hide UI components) and to conduct simple AJAX requests. It also calls browser APIs in a cross-browser consistent manner. jQuery created waves when it first emerged! It was a forerunner to JavaScript community packages, propelling client-side development to new heights.The JavaScript ecosystem has evolved and altered dramatically. Initially, most existing frameworks established their own jQuery-like features, and browsers made their APIs more consistent.On the other hand, we now approach web development from a fresh perspective. We believe that directly modifying the DOM is not the best development path. Because DOM elements carry a lot of useless data, when the web page is packed with elements, the performance suffers.React is distinct in that it is a UI component management library rather than a utility library that wraps browser APIs. When you use React, you must follow a recommended technique (component-oriented structure) for building your user interface and structure your interactions around well-defined lifecycle functions. If you follow the recommended conventions, you will receive optimizations for free, e.g. it reduces the actual DOM changes that occur to maintain the application performant.A single component in React encompasses both the functional aspect of the View and the UI itself. That's correct! Your UI elements in React are written in JSX, a syntax extension of HTML. Although it may appear to be counter-intuitive, it turns out to be far more efficient, and you have greater control and maintenance over your code.Handling the DOMThe main distinction between these two is that React operates through the "virtual DOM," whereas jQuery interacts directly with the DOM. The virtual DOM is a memory-based DOM implementation that compares to existing DOM elements and makes the appropriate changes/updates. As a result, performance is substantially faster.jQuery is not appropriate for large-scale applications. It results in spaghetti code generation because standard DOM does not allow complex codes either.React's component-oriented architecture and virtual DOM implementation make it appropriate for developing large-scale apps.Affairs of the StateChanging the value of a JavaScript variable within a page might be difficult. Assume you have a variable called message in your application that represents a shoutout. You want that message to be shown within a container like this:Message goes herejQuery:Everything is still read from top to bottom in a jQuery approach. You might use the following code to extract the current message first:var message = $("#message").html();To update the message, you must refer to the once more and insert the new value:var message = "New message"; // Normally set by some other logical routine$("#message").html(message);One disadvantage of this approach is that the message must be set twice: once to extract the value and again to assign a new value to it. In addition, further code is required to insert the message back into the target . This can quickly become a mess, especially if you have another process that may create a new value for the message. In such situation, you'd need to execute $("#message").html(message) once more.React.js:React.js overcomes this problem by keeping a single instance of a variable in the state of a component. A state object is defined within each React.js component and is initialized in the component's constructor. For example, imagine you want to keep the same message value, and any logical routine that changes it will be reflected in the component's UI. You could have any of the following:import React from 'react';export default class MessageComponent extends React.Component {constructor(props) {     super(props);       this.state = {       message: ""     }   }     updateMessage(message) {     this.setState({       message: message     });   }   render() {     return (               {this.state.message}           );   } }You'll see that you initialised the message in the component's state within the constructor. The component has a method named updateMessage(message), which calls the setState() function of another component to update the value of message. The idea is that whenever setState() is invoked, the component would re-render the UI as called by render(), because render() provides JSX that displays the message via this.state.message with whatever value it now has.Handling EventsThe actions taken by the site visitor throughout their interaction with the website (orr webpage) are referred to as events. There might be a variety of events, such as:The user clicks a button.The mouse pointer is moved over an image by the user.The user pressed any key on the keyboard, and so on.To handle DOM events using jQuery methods, first obtain a reference to the DOM element(s) using a jQuery selector and then activate the appropriate jQuery event function.Example: Handle Button Click Event$('#Btn').click(function () {     alert('Button clicked'); }); In this case, we first utilise the id selector to obtain a reference to the 'Save' button, and then we use the click method. We've defined the handler function as a callback function that will be called whenever the Save button's click event is triggered.Event objectEvery event handler method receives an event object from jQuery. The event object contains critical properties and methods for cross-browser consistency, such as target, pageX, pageY, relatedTarget, and so on.React’s SyntheticEvent System:An instance of SyntheticEvent, a cross-browser wrapper for the browser's native event, is supplied to an event handler in React. It provides the same interface as the native event in the browser, including stopPropagation() and preventDefault(). You cannot return false in React to disable default behavior. Instead, preveutilizentDefault must be explicitly invoked.If you require the underlying browser event for any reason, simply utilise the nativeEvent attribute to obtain it. The synthetic events are distinct from, and do not correspond directly to, the native events of the browser. OnMouseLeave event.nativeEvent, will point to a mouseout event. The specific mapping is not included in the public API and is subject to change at any time. Each SyntheticEvent object has the following propertiesboolean bubblesboolean cancelableDOMEventTarget currentTargetboolean defaultPreventednumber eventPhaseboolean isTrustedDOMEvent nativeEventvoid preventDefault()boolean isDefaultPrevented()void stopPropagation()boolean isPropagationStopped()void persist()DOMEventTarget targetnumber timeStampstring typeThe SyntheticEvent is aggregated. This implies that the SyntheticEvent object will be reused, and all properties will be negated when the event callback is called. This behavior is intended to improve performance. As a result, a SyntheticEvent cannot be used asynchronously. By clicking on the console event, you are gaining asynchronous access to it.Side EffectsA side effect is making an HTTP request and saving the response to the component's state.In ReactComponents in React have methods that are executed during the component's various phases. These are referred to as lifecycle methods.It takes a lot of practice to find out when and how to employ different lifecycle methods. Regardless, componentDidMount with class components and useEffect with functional components are the most important for HTTP requests.Example:We generated the component in App.js and styled it in App.css, using the API endpoint from http://jsonplaceholder.typicode.com/users. We can receive data from API endpoints with the targets "id", "name", "username", and "email".Step 1: npx create-react-app api-appAfter executing this command successfully, you will see a folder structure like this:Step 2: cd api-appStep 3: Write the following code in App.js in src folder:import React from "react"; import './App.css'; class App extends React.Component { // Constructor constructor(props) { super(props); this.state = { items: [], DataisLoaded: false }; } // ComponentDidMount is used to // execute the code componentDidMount() { fetch( "https://jsonplaceholder.typicode.com/users") .then((res) => res.json()) .then((json) => { this.setState({ items: json, DataisLoaded: true }); }) } render() { const { DataisLoaded, items } = this.state; if (!DataisLoaded) return Pleses wait some time.... ; return ( Fetch data from an api in react { items.map((item) => ( User_Name: { item.username }, Full_Name: { item.name }, User_Email: { item.email } )) } ); } } export default App;Step 4: Write the following code in App.css in src folder:.App { text-align: center; color: Green; } .App-header { background-color: #282c34; min-height: 100vh; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: calc(10px + 2vmin); color: white; } .App-link { color: #61dafb; } @keyframes App-logo-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } } export default App;  Step 5: Run the app using npm startOutput: You can see the output in http://localhost:3000/In jQueryThe basic AJAX functionality of jQuery is one of its best features. This makes it simple to incorporate data from other websites and services into your own. It will also allow you to become less reliant on the widgets provided by companies, allowing you to design your own.AJAX (Asynchronous JavaScript and XML) is a collection of tools for making server calls and retrieving data.Example:We'll use a free API to pull employee names from an employee object and show them in a list. On the internet, there are numerous APIs that are available for free. You can utilize any of them.Let's look at the steps for Ajax Code and later on, we can add the HTML code to complete it.The first step is to obtain the getElementById method for the button element.The next step is to add an eventListener to the button and provide it with a callback function.Using the new keyword, create an XHR object.Using the open function, open an object. The first parameter is the type (GET or POST), the second is the API URL, and the third is a boolean value (true means asynchronous call and false means synchronous call).To display the data, we'll now use the onload function. After the API call is completed, the onload method is called. The success code for an HTTP request is 200, therefore we're testing it with that.We'll now convert it to a JSON object so we can quickly retrieve info from it.We'll use a loop to go over all of the items in the object and add them to the list using the innerhtml property in this step.The final step is to use the send() function to send the request.Complete code: AJAX in jQuery Fetch Data Employee List let fetchBtn = document.getElementById("fetchBtn"); fetchBtn.addEventListener("click", buttonclickhandler); function buttonclickhandler() { // Instantiate an new XHR Object const xhr = new XMLHttpRequest(); // Open an obejct (GET/POST, PATH, // ASYN-TRUE/FALSE) xhr.open("GET", "http://dummy.restapiexample.com/api/v1/employees", true); // When response is ready xhr.onload = function () { if (this.status === 200) { // Changing string data into JSON Object obj = JSON.parse(this.responseText); // Getting the ul element let list = document.getElementById("list"); str = "" for (key in obj.data) { str += `${obj.data[key].employee_name}`; } list.innerHTML = str; } else { console.log("File not found"); } } xhr.send(); } When you click on the Fetch Data button, you will see a list of employees from a free API which we have used in our code.So, that’s how you can work with an API in jQuery.Migrating from jQuery to ReactReferencing DOM ElementsConsider the following HTML document: Click MeIn jQuery:var $btnClick = $("#btn-click");$btnClick.on("click", function() {  alert("Button was clicked!");});A programmer should first use the $() method to access to the DOM element, giving either an id reference # or a class reference, as shown in jQuery. The click-event handler is instead given as the first parameter string to the on() function call of a query element.In React.js:In React.js, the displayed HTML UI is handled as part of the container, which is known as a component. All the elements which can only be presented in a target will be included in the component. The element will be removed from the original HTML code. Alternatively, you might use the element as follows:You'd have to create a component that renders the button in a separate JavaScript file first:import React from 'react';export default class ButtonComponent extends React.Component {  constructor(props) {    super(props);  }  handleButtonClicked() {    alert("Button was clicked!");  }  render() {    return (                        Click Me                  );  }}Throughout the function call, a.bind(this) is often used to retain the value of this constant. This method exposes other methods that are either built-in to a React.Component, such as setState(), or user-defined. It could be claimed that an explicit reference was unnecessary. React.js and jQuery vary in that React.js saves all of its UI demands, but jQuery expects also that UI element is displayed in HTML.Managing StateAssume you have a variable called message in your application that represents a shoutout. You'd like that message to appear within a container div like this:Message goes hereIn jQueryIn a jQuery approach, everything is still read from top to bottom.var message = $("#message").html();You must re-reference the and insert the new value to update the message:var message = "New message"; // Normally set by some other logical routine$("#message").html(message);This method has the drawback of requiring the message to be set twice: once to extract the value and also to give a new value. The message must also be returned to the target , which necessitates the use of additional code. This can get a little complex, especially if you have another procedure that might affect the value of the message. In that situation, you'd have to call $("#message").html(message) once more.In React.jsReact.js overcomes this problem by maintaining only one instance of a variable in a component's state. Each React.js component has a state object that is created in the component's state object. Consider the instance where you wish to preserve same message value, but any logical routine that modifies it will be reflected in the component's UI. One or more of the following may be present:import React from 'react';export default class MessageComponent extends React.Component {  constructor(props) {    super(props);    this.state = {      message: ""    }  }  updateMessage(message) {    this.setState({      message: message    });  }  render() {    return (              {this.state.message}          );  }}We can set the message in the component's state in the constructor. The updateMessage(message) method of the component invokes the setState() method of the component to update the message's value. The concept is that whenever setState() is invoked, the component will re-render the UI as it was in render(), because render() produces JSX, which displays the message via this.state.message with whatever value it has at the time.React vs jQuery – which to use whenOnce you've ported a large amount of code to React, you can start building component trees and communicating with props and callbacks between them.React.js might seem confusing intially, but still it uses good state management to keep things structured in the long term. Although jQuery is straightforward to use, it becomes unstable when more code is brought into the equation.If you're planning to switch from jQuery to React.js, keep the following in mind:Create your components as stand-alone UI elements that can be positioned anywhere on your page.To control how values are rendered by a component, use state variables and utility methods within the component.A call to setState() causes the component's UI to be re-rendered with the updated state values using render().
1998
Migrating From jQuery to React? Here’s How!

jQuery isn’t React and React isn’t jQuery:We u... Read More

Handling React Events - A Detailed Guide

Event handling essentially allows the user to interact with a webpage and do something specific when a certain event like a click or a hover happens. When the user interacts with the application, events are fired, for example, mouseover, key press, change event, and so on. The application must handle events and execute the code. In short, events are the actions to which javascript can respond.   The actions to which javascript can respond are called events. Handling events with react is  very similar to handling events in DOM elements. Below are some general events that you would see in and out when dealing with react based websites:  Clicking an element  Submitting a form Scrolling page Hovering an element  Loading a webpage Input field change User stroking a key Image loading Naming Events in React Handling events with react is very similar to handling events in DOM elements, although there are some syntactic differences.   React events are written in camelCase.   A function is passed as the event handler rather than string. The way to write events in html / DOM is below:        click me onclick is written in lower case in html as shown above and what action to take when this onclick event triggers is taken care of by handleClick.In React, events are named using camel case and you pass a function as event handler as shown below:  Like in a functional component, event is written like below:       click me   In class based component ,event is written like below        click me Defining Events:Events are normally used in combination with functions, and the function is not executed until the event occurs, and the combination of event, HTML element, and javascript function is called binding which means to map all three. Generic syntax is:      Example:  Create a button element and what happens when onClick event triggered is driven by the function which is func() shown below     click me Let’s see some of the event attributes:   onmouseover : The mouse is moved over an element onmouseup : The mouse button is released onmouseout : The mouse  is moved off an element onmousemove: The mouse is moved Onmousedown: mouse button is pressed  onload : A image is done loading onunload: Existing the page  onblur : Losing Focus  on element  onchange : Content of a field changes onclick: Clicking an object  ondblclick: double clicking an object  onfocus element getting a focus  Onkeydown: pushing a keyboard key Onkeyup: keyboard key is released Onkeypress: keyboard key is pressed  Onselect: text is selected These are some examples of events:                                         Events                               function testApp (){                        alert((“Hello Event”);                                                   test Clicked                  test double Clicked                     Synthetic Events When you specify an event in JSX, you are not directly dealing with regular DOM events, you are dealing with a react event type called a synthetic event.It's a simple wrapper for native event instances and every synthetic event created needs to be garbage-collected which can be resource intensive in terms of CPU. The synthetic event object has properties mentioned below:  Boolean isTrusted  DOMEvent nativeEvent number timeStamp   void preventDefault() number eventPhase Synthetic events provide an interface and reduce browser inconsistencies and the event contains required information for its propagation to work. Synthetic event is reused for performance reasons in the browser, A synthetic event is a cross-browser wrapper around the browser’s native event it has the same interface as the native event. Synthetic events are delegated to the document node. Therefore native events are triggered first and the events bubble up to document, after which the synthetic events are triggered. The synthetic event object will be reused and all the properties will be nullified after the event callback has been invoked and this is for performance reasons.The workflow of synthetic event in react is:    Element ---- > Event ---- > synthetic event  ---- > handler(e)                                |                                                      |                                |  _______  Component ________|  umber timeStamp The Basics of React Event Handling Let’s explore how to handle events in react and we will showcase the click event and how it holds good for other types of events. Let’s start with functional components by creating a  file as clickAppHandler.js.In this file let’s create a  functional component  as shown below                        Import React from ‘...react’                         function clickAppHandler() {                                function clickHandler() {                                        console.log(‘clicked’)                                         }                                  return (                                                                                  Click                                                                          )                         }                       export default clickAppHandler  When onClick event triggers clickHandler function is called as shown below and when you click the button console will print the string “clicked” After this you need the add a component in the app component. In our code above you can see on click we pass the function as event handler and you will notice that we haven't added parentheses as it becomes a function, and we do not want that and we want handler to be a function not a function call. When a new component is rendered its event handler functions are added to the mapping maintained by the react.When the event is triggered and it hits and DOM object ,react maps the event to the handler, if it matches it calls the handler. The event handling in react is declarative and the advantage of declarative way to handlers is that they are part of the User interface structure.  Let’s take a look at event handling in class components                       Import React, { Component } from ‘...react’                         class TestApp extends Component {                              clickHandler() {                                  console.log(“clicked”)                                }                                render(){                                      return(                                                                                     Click me                                                                                 )                                 }                            }                       export default TestApp You cannot return false to prevent default behaviour in React. You must call preventDefault explicitly.  In HTML it looks like below:    Click Output: It will print “Clicked”  And in React, like this:  function clickHandle(e) {       e.preventDefault();       console.log(“Handled”);   }  Click  Output : console will print “Handled”  There are some  event handlers triggered by an event in the bubbling phase which is the same as with the normal DOM API; simply attach a handler to an eventual parent of an element and any events triggered on that element will bubble to the parent as long as it's not stopped via stopPropagation along the way   Click me  Below are some of the event handlers triggered in the bubbling phase:  MouseEvents           onClick           onDrag          onDoubleClick Keyboard Events                    onKeyDown                    onKeyPress                    onKeyUp Focus Events                  onFocus   onBlur To capture an event handler for the capture phase, append capture to the event name. For example, instead of using onClick, use onClickCapture to handle the click event.  Capture event example:                  Click me    Additional ExamplesExample1                       Import React from ‘...react’                         function clickAppHandler() {                                function clickHandler() {                                        console.log(‘clicked’)                                         }                                  return (                                                                                  Click                                                                          )                         }                       export default clickAppHandler   Example2       This example is along with HTML in a single file                                                            Events                               function testApp (){                        alert((“Hello Event”);                                                   test Clicked                  test double Clicked                     Adding Events: Below example is how you add an event. Highlighted in bold                      Import React from ‘...react’                         function clickAppHandler() {                                function clickHandler() {                                        console.log(‘clicked’)                                         }                                  return (                                                                                  Click                                                                          )                         }                       export default clickAppHandler  Passing Arguments to Event HandlerThere are two ways arguments are passed to event handler  Arrow function                    this.handleClick(id,e)}>Click                onClick is the event                e is the event object                 id can be state or props or some data Bind method      Click  In this case event object is automatically passed In both methods e represents the react event and its passed after the ID as second argument,With an arrow function this event e is passed explicitly but with bind method its automatically passed.                                     Import React,{ Component } from “react”;                                         class TestApp extends Component {                                           state = {                                                       id: 2,                                                      Name: “TestApp Dummy”                                                };                                                             //arrow function                                                 handleClick = (id,e) => {                                                       console.log(id);                                                       console.log(e);                                                  };                                               handleArg = (e) => { this.handleClick(this.state.id,e);}                                                          render() {     return (                    TestApp,{this.state.name}            onClick={this.handleArg}>Display            );   }  }  The react event is an object and obtained from react. Instead of creating a separate function for passing argument, you can directly pass the anonymous arrow function as shown in the render function below:     render() {        return (                                                                                                       TestApp,{this.state.name}                                                {                           this.handleClick(this.state.id,e);                                                               }}>Display                                                                                                         );                                                 }                                            }    Output:   click on button  “TestApp Dummy “                   Let’s see only how bind method looks like in the render function    render() {                                         return (                                                                                                 TestApp,{this.state.name}                                                   Display                                                                                                       );                                                  }                                              } Output: this will display the h1 tag and when you click the button handleClick function gets invoked and the console will display id of the state object as shown above. Building a Practice to Thoroughly Understand Events This blog focuses on event handling, which in turn teaches about event handlers declared in JSX markup.This approach helps in tracking down the element mapped with events in an easy way.  We also learned how to handle multiple event handlers in a single element by using JSX attributes.we also learned about ways to bind event handler and  parameter values. Then we learned about synthetic events which are abstractions around native events. The best way you can retain this learning is by practicing more and tackling the complexities that may arise as you practice. You can find several tutorials on the internet or share your questions with us here. Happy learning! 
5356
Handling React Events - A Detailed Guide

Event handling essentially allows the user to inte... Read More

MongoDB Query Document Using Find() With Example

MongoDB's find() method selects documents from a collection or view and returns a cursor to those documents. There are two parameters in this formula: query and projection.Query – This is an optional parameter that specifies the criteria for selection. In simple terms, a query is what you want to search for within a collection.Projection – This is an optional parameter that specifies what should be returned if the query criteria are satisfied. In simple terms, it is a type of decision-making that is based on a set of criteria.MongoDB's Flexible SchemaA NoSQL database, which stands for "not only SQL," is a way of storing and retrieving data that is different from relational databases' traditional table structures (RDBMS).When storing large amounts of unstructured data with changing schemas, NoSQL databases are indeed a better option than RDBMS. Horizontal scaling properties of NoSQL databases allow them to store and process large amounts of data.These are intended for storing, retrieving, and managing document-oriented data, which is frequently stored in JSON format (JavaScript Object Notation). Document databases, unlike RDBMSs, have a flexible schema that is defined by the contents of the documents.MongoDB is one of the most widely used open-source NoSQL document databases. MongoDB is known as a 'schemaless' database because it does not impose a specific structure on documents in a collection.MongoDB is compatible with a number of popular programming languages. It also offers a high level of operational flexibility because it scales well horizontally, allowing data to be spread or 'sharded' across multiple commodity servers with the ability to add more servers as needed. MongoDB can be run on a variety of platforms, including developer laptops, private clouds, and public clouds.Querying documents using find()MongoDB queries are used to retrieve or fetch data from a MongoDB database. When running a query, you can use criteria or conditions to retrieve specific data from the database.The function db.collection is provided by MongoDB. find() is a function that retrieves documents from a MongoDB database.In MongoDB, the find method is used to retrieve a specific document from the MongoDB collection. In Mongo DB, there are a total of six methods for retrieving specific records.find()findAndModify()findOne()findOneAndDelete()findOneAndReplace()findOneAndUpdate()Syntax:find(query, projection)We can fetch a specific record using the Find method, which has two parameters. If these two parameters are omitted, the find method will return all of the documents in the MongoDB collection.Example:Consider an example of employees with the database of employee_id and employee_name and we will fetch the documents using find() method.First, create a database with the name “employees” with the following code:use employeesNow, create a collection “employee” with:db.createCollection("employee")In the next step we will insert the documents in the database:db.employee.insert([{employee_id: 101, employee_name: "Ishan"}, {employee_id: 102, employee_name: "Bhavesh"}, {employee_id: 103, employee_name: "Madan"}])Find all Documents:To get all the records in a collection, we need to use the find method with an empty parameter. In other words, when we need all the records, we will not use any parameters.db.employee.find()Output in Mongo ShellThe pretty() method can be used to display the results in a formatted manner.Syntax:db.COLLECTION_NAME.find().pretty()Let’s check our documents with pretty() method:Query FiltersWe will see examples of query operations using the db.collection.find() method in mongosh.We will use the employee collection in the employees database.db.employee.insert([{employee_id: 101, employee_name: "Ishan", age: 21, email_id: "ishanjain@gmail.com"}, {employee_id: 102, employee_name: "Bhavesh", age: 22, email_id: "bhaveshg@gmail.com"}, {employee_id: 103, employee_name: "Madan", age: 23, email_id: "madan@gmail.com"}])As we have seen earlier that to select all the documents in the database we pass an empty document as the query filter parameter to the find method.db.employee.find().pretty()Find the first document in a collection:db.employee.findOne()Find a document by ID:db.employee.findOne({_id : ObjectId("61d1ae0b56b92c20b423a5a7")})Find Documents that Match Query Criteriadb.employee.find({“age”: “22”})db.employee.find({"employee_name": "Madan"}).pretty()Sort Results by a Field:db.employee.find().sort({age: 1}).pretty()order by age, in ascending orderdb.employee.find().sort({age: -1}).pretty()order by age, in descending orderAND Conditions:A compound query can specify conditions for multiple fields in the documents in a collection. A logical AND conjunction connects the clauses of a compound query indirectly, allowing the query to select all documents in the collection that meet the specified conditions.In the following example, we will consider all the documents in the employee collection where employee_id equals 101 and age equals 21.db.employee.find({"employee_id": 101, "age": "21" }).pretty()Querying nested fieldsThe embedded or nested document feature in MongoDB is a useful feature. Embedded documents, also known as nested documents, are documents that contain other documents.You can simply embed a document inside another document in MongoDB. Documents are defined in the mongo shell using curly braces (), and field-value pairs are contained within these curly braces.Using curly braces, we can now embed or set another document inside these fields, which can include field-value pairs or another sub-document.Syntax:{ field: { field1: value1, field2: value2 } }Example:We have a database “nested” and in this database we have collection “nesteddoc”.The following documents will insert into the nesteddoc collection.db.nesteddoc.insertMany([ { "_id" : 1, "dept" : "A", "item" : { "sku" : "101", "color" : "red" }, "sizes" : [ "S", "M" ] }, { "_id" : 2, "dept" : "A", "item" : { "sku" : "102", "color" : "blue" }, "sizes" : [ "M", "L" ] }, { "_id" : 3, "dept" : "B", "item" : { "sku" : "103", "color" : "blue" }, "sizes" : "S" }, { "_id" : 4, "dept" : "A", "item" : { "sku" : "104", "color" : "black" }, "sizes" : [ "S" ] } ])Place the documents in the collection now. Also, take a look at the results:As a result, the nesteddoc collection contains four documents, each of which contains nested documents. The find() method can be used to access the collection's documents.db.nesteddoc.find()Specify Equality Condition:In this example, we will select the document from the nesteddoc query where dept equals “A”.db.nesteddoc.find({dept: "A"})Querying ArraysUse the query document {: } to specify an equality condition on an array, where is the exact array to match, including the order of the elements.The following query looks for all documents where the field tags value is an array with exactly two elements, "S" and "M," in the order specified:db.nesteddoc.find( { sizes: ["S", "M"] } )Use the $all operator to find an array that contains both the elements "S" and "M," regardless of order or other elements in the array:db.nested.find( { sizes: { $all: ["S", "M"] } } )Query an Array for an Element:The following example queries for all documents where size is an array that contains the string “S” as one of its elements:db.nesteddoc.find( { sizes: "S" } )Filter conditionsTo discuss the filter conditions, we will consider a situation that elaborates this. We will start by creating a collection with the name “products” and then add the documents to it.db.products.insertMany([ { _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] }, { _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] }, { _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] }, { _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] }, { _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }])To check the documents, use db.products.find():$gt$gt selects documents with a field value greater than (or equal to) the specified value.db.products.find( { qty: { $gt: “20” } } )$gte:$gte finds documents in which a field's value is greater than or equal to (i.e. >=) a specified value (e.g. value.)db.products.find( { qty: { $gte: 20 } } )$lt:$lt selects documents whose field value is less than (or equal to) the specified value.db.products.find( { qty: { $lt: 25 } } )$lte:$lte selects documents in which the field's value is less than or equal to (i.e. =) the specified value.db.products.find( { qty: { $lte: 20 } } )Query an Array by Array Length:To find arrays with a specific number of elements, use the $size operator. For example, the following selects documents with two elements in the array.db.products.find( { "tags": {$size: 2} } )ProjectionIn MongoDB, projection refers to selecting only the data that is required rather than the entire document's data. If a document has five fields and you only want to show three of them, select only three of them.The find() method in MongoDB accepts a second optional parameter, which is a list of fields to retrieve, as explained in MongoDB Query Document. When you use the find() method in MongoDB, it displays all of a document's fields. To prevent this, create a list of fields with the values 1 or 0. The value 1 indicates that the field should be visible, while 0 indicates that it should be hidden.Syntax:db.COLLECTION_NAME.find({},{KEY:1})Example:We will consider the previous example of products collection. Run the below command on mongoshell to learn how projection works:db.products.find({},{"tags":1, _id:0})Keep in mind that the _id field is always displayed while executing the find() method; if you do not want this field to be displayed, set it to 0.Optimized FindingsTo retrieve a document from a MongoDB collection, use the Find method.Using the Find method, we can retrieve specific documents as well as the fields that we require. Other find methods can also be used to retrieve specific documents based on our needs.By inserting array elements into the query, we can retrieve specific elements or documents. To retrieve data for array elements from the collection in MongoDB, we can use multiple query operators.
6498
MongoDB Query Document Using Find() With Example

MongoDB's find() method selects documents from a c... Read More

Implementing MongoDb Map Reduce using Aggregation

Algorithms and applications in today's data-driven market collect data about people, processes, systems, and organisations 24 hours a day, seven days a week, resulting in massive amounts of data. The problem is figuring out how to process this massive amount of data efficiently without sacrificing valuable insights.What is Map Reduce? The MapReduce programming model comes to the rescue here. MapReduce, which was first used by Google to analyse its search results, has grown in popularity due to its ability to split and process terabytes of data in parallel, generating results faster. A (Key,value) pair is the basic unit of information in MapReduce. Before feeding the data to the MapReduce model, all types of structured and unstructured data must be translated to this basic unit. The MapReduce model, as the name implies, consists of two distinct routines: the Map-function and the Reduce-function.  MapReduce is a framework for handling parallelizable problems across huge files using a huge number of devices (nodes), which are collectively referred to as a cluster (if all nodes are on the same local network and use similar hardware) or a grid (if the nodes are shared across geographically and administratively distributed systems, and use more heterogeneous hardware).  When data stored in a filesystem (unstructured) or a database(structured) is processed, MapReduce can take advantage of data's locality, processing it close to where it's stored to reduce communication costs. Typically, a MapReduce framework (or system) consists of three operations: Map: Each worker node applies the map function to local data and saves the result to a temporary storage. Only one copy of the redundant input data is processed by a master node. Shuffle: worker nodes redistribute data based on output keys (produced by the map function), ensuring that all data associated with a single key is stored on the same worker node. Reduce: each group of output data is now processed in parallel by worker nodes, per key. This article will walk you through the Map-Reduce model's functionality step by step. Map Reduce in MongoDB The map-reduce operation has been deprecated since MongoDB 5.0. An aggregation pipeline outperforms a map-reduce operation in terms of performance and usability. Aggregation pipeline operators like $group, $merge, and others can be used to rewrite map-reduce operations. Starting with version 4.4, MongoDB provides the $accumulator and $function aggregation operators for map-reduce operations that require custom functionality. In JavaScript, use these operators to create custom aggregation expressions. The map and reduce functions are the two main functions here. As a result, the data is independently mapped and reduced in different spaces before being combined in the function and saved to the specified new collection. This mapReduce() function was designed to work with large data sets only. You can perform aggregation operations like max and avg on data using Map Reduce, which is similar to groupBy in SQL. It works independently and in parallel on data. Implementing Map Reduce with Mongosh (MongoDB Shell)  The db.collection.mapReduce() method in mongosh is a wrapper for the mapReduce command. The examples that follow make use of the db.collection.mapReduce(). Example: Create a collection ‘orders’ with these documents: db.orders.insertMany([     { _id: 1, cust_id: "Ishan Jain", ord_date: new Date("2021-11-01"), price: 25, items: [ { sku: "oranges", qty: 5, price: 2.5 }, { sku: "apples", qty: 5, price: 2.5 } ], status: "A" },     { _id: 2, cust_id: "Ishan Jain", ord_date: new Date("2021-11-08"), price: 70, items: [ { sku: "oranges", qty: 8, price: 2.5 }, { sku: "chocolates", qty: 5, price: 10 } ], status: "A" },     { _id: 3, cust_id: "Bhavesh Galav", ord_date: new Date("2021-11-08"), price: 50, items: [ { sku: "oranges", qty: 10, price: 2.5 }, { sku: "pears", qty: 10, price: 2.5 } ], status: "A" },     { _id: 4, cust_id: "Bhavesh Galav", ord_date: new Date("2021-11-18"), price: 25, items: [ { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" },     { _id: 5, cust_id: "Bhavesh Galav", ord_date: new Date("2021-11-19"), price: 50, items: [ { sku: "chocolates", qty: 5, price: 10 } ], status: "A"},     { _id: 6, cust_id: "Madan Parmar", ord_date: new Date("2021-11-19"), price: 35, items: [ { sku: "carrots", qty: 10, price: 1.0 }, { sku: "apples", qty: 10, price: 2.5 } ], status: "A" },     { _id: 7, cust_id: "Madan Parmar", ord_date: new Date("2021-11-20"), price: 25, items: [ { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" },     { _id: 8, cust_id: "Abhresh", ord_date: new Date("2021-11-20"), price: 75, items: [ { sku: "chocolates", qty: 5, price: 10 }, { sku: "apples", qty: 10, price: 2.5 } ], status: "A" },     { _id: 9, cust_id: "Abhresh", ord_date: new Date("2021-11-20"), price: 55, items: [ { sku: "carrots", qty: 5, price: 1.0 }, { sku: "apples", qty: 10, price: 2.5 }, { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" },     { _id: 10, cust_id: "Abhresh", ord_date: new Date("2021-11-23"), price: 25, items: [ { sku: "oranges", qty: 10, price: 2.5 } ], status: "A" }  ]) Apply a map-reduce operation to the orders collection to group them by cust_id, then add the prices for each cust_id: To process each input document, define the map function: this refers the document that the map-reduce operation is processing in the function. For each document, the function maps the price to the cust_id and outputs the cust_id and price. var mapFunction1 = function() {emit(this.cust_id, this.price);}; With the two arguments keyCustId and valuesPrices, define the corresponding reduce function: The elements of the valuesPrices array are the price values emitted by the map function, grouped by keyCustId. The valuesPrice array is reduced to the sum of its elements by this function. var reduceFunction1 = function(keyCustId, valuesPrices) {return Array.sum(valuesPrices);};Apply the mapFunction1 map function and the reduceFunction1 reduce function to all documents in the orders collection: db.orders.mapReduce(mapFunction1,reduceFunction1,{ out: "map_reduce_example" }) The results of this operation are saved in the map_reduce_example collection. If the map_reduce_example collection already exists, the operation will overwrite its contents with the map-reduce operation's results. Check the map_reduce_example collection to verify: db.map_reduce_example.find().sort( { _id: 1 } ) Aggregation Alternative:You can rewrite the map-reduce operation without defining custom functions by using the available aggregation pipeline operators: db.orders.aggregate([{$group: { _id:"$cust_id",value:{$sum: "$price" } } },{ $out: "agg_alternative_1" }]) Check the agg_alternative_1 collection to verify: db.agg_alternative_1.find().sort( { _id: 1 } )Implementing Map Reduce with Java Consider the collection car and insert the following documents in it. db.car.insert( [ {car_id:"c1",name:"Audi",color:"Black",cno:"H110",mfdcountry:"Germany",speed:72,price:11.25}, {car_id:"c2",name:"Polo",color:"White",cno:"H111",mfdcountry:"Japan",speed:65,price:8.5}, {car_id:"c3",name:"Alto",color:"Silver",cno:"H112",mfdcountry:"India",speed:53,price:4.5}, {car_id:"c4",name:"Santro",color:"Grey",cno:"H113",mfdcountry:"Sweden",speed:89,price:3.5} , {car_id:"c5",name:"Zen",color:"Blue",cno:"H114",mfdcountry:"Denmark",speed:94,price:6.5} ] ) You will get an output like this:  Let's now write the map reduce function on a collection of cars, grouping them by speed and classifying them as overspeed cars.  var speedmap = function (){  var criteria;  if ( this.speed > 70 ) {criteria = 'overspeed';emit(criteria,this.speed);}}; Based on the speed, this function classifies the vehicle as an overspeed vehicle. The term "this" refers to the current document that requires map reduction. var avgspeed_reducemap = function(key, speed) {       var total =0;       for (var i = 0; i 
7347
Implementing MongoDb Map Reduce using Aggregation

Algorithms and applications in today's data-driven... Read More