Search

Featured blog posts

SAFe® Agilist Certification Vs PMI-ACP®: Which Certification Should You Choose?

The competition for jobs is getting tough in today’s world. Whether you are a job seeker, corporate employee, or a consultant, you should keep y... Read More

A Journey Towards Earning a Leading SAFe®5.0 Certification

Our blog regularly provides insights about the Scaled Agile Framework (SAFe®), like 4 main features that enable SAFe®. You can also go th... Read More

Leading SAFe® 4.6 Infographic—An In-Depth Guide To Become SAFe® Agilist

Most of the organizations start their Agile journey with a small team. Once they get success with the methodology that they are implementing in the or... Read More

How To Pass Leading SAFe® 4 Exam ?

Scaled Agile Framework is a roadmap that leads the organizations in implementing the Lean and Agile Practices. SAFe® includes the three foundation... Read More

5 Signs You Need Help With Leading SAFe® 4.5

When SAFe® 4.0 was launched, it helped the organizations to deliver innovations for Lean software and systems engineering. It depicted a noteworth... Read More

SP, SPC, PM/PO: Which Leading SAFe® Certification Is Right For You?

Are you thinking of pursuing Agile certifications? Then you must have already made up your mind to opt for professional certifications in Scaled Agile... Read More

DevOps Roadmap to Become a Successful DevOps Engineer

“DevOps is a combination of best practices, culture, mindset, and software tools to deliver a high quality and reliable product faster&rdqu... Read More

12 DevOps Skills That A DevOps Engineer Should Master

Are you an engineer looking out to excel in DevOps skills? Is your team looking to adopt DevOps? You have come to the right place. In this article, we... Read More

DevOps Engineer Salary

Before we start discussing the salary of DevOps Engineer, let’s understand what DevOps is? DevOps is a software development strategy which bridg... Read More

Top Devops Tools You Must Know

In the last decade for most of the enterprises, the term DevOps has transformed from just a buzzword to a way of working. The concept of DevOps origin... Read More

Topics

Latest Posts

Back Up, Restore, and Migrate a MongoDB Database

Popular among both enterprises and startups, MongoDB is a database that is perfectly suited for web-apps that need to scale once the user base increases. MongoDB is different from traditional relational databases because it uses json like objects to store data, instead of tables in relational databases. In this post, we will learn to backup and restore a MongoDB database. In all software products there is an import and export feature, which in database terms, deals with human-readable format. On the other hand, the backup and restore operations use MongoDB specific data, which preserve the MongoDB attributes.  So, when migrating the database, we should prefer backup and restore over import and export. But we should also keep in mind that our source and target systems are compatible, which means that both should be Windows or both should be a Linux based system like Ubuntu/Mac. Prerequisites We are using Windows 10 in this tutorial. Please make sure you have downloaded the MongoDB Community Server and installed in it. It is a very easy setup and you will find lot of good articles on the internet detailing this out. Please ensure that you have added it in the Environment variable in your PC. Backup Considerations In a production environment, backups act as a snapshot of the database at a certain point. Large and complex databases do fail or can be hacked. If that happens, we can use the last backup file to restore the database to the point, before it failed. These are some of the factors which should be taken into consideration when doing a recovery. Recovery Point Objective We should know the objective of the recovery point, which means how much data we are willing to lose during a backup and restoration. A continuous backup is preferred for critical data like bank information and backups should be taken several times during the day. On the other hand, if the data doesn’t change frequently, then the backup can be taken every 6 months. Recovery Time ObjectiveThis tells how quickly the restoration can be done. During restoration the application will be down for some time; and this downtime should be minimized, or else customer relationships will be lost. Database and Snapshot IsolationThis refers to the distance between the primary database server and the backup server. If they are close enough i.e., in the same building, then the recovery time reduces. However, in the event of a physical event such as a fire, there is a likelihood of it been destroyed with the primary database.  Restoration Process We should always test our backups in test servers to see if they will work, in case a restoration is required. Available Storage Backup of database generally takes a lot of space and in most cases, it will never be required. So, we should try to minimize the space taken on the disk, by archiving the database into a zip file. Complexity of DeploymentThe backup strategy should be easy to set and should be automated, so that we don’t have to remember to take the backup after regular intervals. Understanding the Basics The first thing that we should know is that MongoDB uses json and bson(binary json) formats for storing data. So, people coming from a JavaScript background can relate to objects for json, which have a key-value pair. Also, json is the preferred format in which we receive or send data to an API endpoint. You can check the json data of a MongoDB database in any tool or online editors. Even the famous Windows application Notepad++ has a json viewer. An example of a json document looks like below. As we can see from the above example, json is very convenient to work with, especially for developers.  But it doesn’t support all the data types available in bson. So, for backup and restoring, we should use binary bson. The second thing to keep in mind is that MongoDB automatically creates databases and collection names if they don’t exist during restore operations. Third, since MongoDB is a document-based database, in many user cases we store large amounts of data in one collection, such as the whole post of an article. MongoDB is also used extensively in large databases and big data. So, reading and inserting the data can consume a lot of CPU, memory and disk space. We should always run the backups during the non-peak hours like night. As already mentioned earlier, we can use import and export functions for backup and restoration of MongoDB databases, but we should use commands like mongodump and mongorestore to backup and restore respectively. MongoDB backup We will first cover backing up the MongoDB database. For this we use the mongodump command.  First open the Windows command prompt and go to the location in which MongoDB is installed. If you have chosen the default setting, while installing MongoDB though the pop-up it will be installed in a location like C:\Program Files\MongoDB\Server\4.4\bin The version number only will change if you are reading this blog in the future. Also, note that it’s better to run the command prompt in the Admin mode. So, once we open the command prompt, we need to change the directory to MongoDB bin folder by giving the below command. cd C:\Program Files\MongoDB\Server\4.4\binNow, enter mongod and press enter. It will show some json text.Now, we can backup to any location. For this post I am backing up on my Desktop in a Backup folder, which I have created through the command line.Now, we have to run mongodump command, but it should be also present in our MongoDB bin folder. If it is not present, we need to download it from and install it. After this, copy the entire exe files from the download to the MongoDB bin folder. MongoDB Backup with no option Now, run the mongodump command from the bin directory. Here, we are not giving any argument so the backup of the whole database will be taken in the same bin directory.MongoDB Backup to an output directory Now, run the mongodump command from the bin directory. Here, the argument –out specifies the directory in which the data backup will be maintained. In our case we are giving the Backup folder in the  Desktop, which we have created earlier. mongodump --out C:\Users\pc\Desktop\Backup Now, go to the desktop and you can find the backup that has been created in our Backup folder.  MongoDB Backup a specific database Now, we can also backup only a database in mongodump using the –db option. I have an example database, so to backup only that I will use the below command. mongodump --db example --out C:\Users\pc\Desktop\Backup As, you can see in the below output only the example database was backed up. MongoDB Backup a specific collection Now, if we want to only backup a specific collection, we need to use the –collection option and give the collection name. Also, note that the database name is mandatory in this case, as mongodb needs to know about the database to search for the collection. I have a products collection within the example database, so to backup only that I will use the below command. mongodump --db example --out C:\Users\pc\Desktop\Backup –collection products As, you can see in the below output only the products collection from example database was backed up. MongoDB Backup from remote MongoDB instances We can get the backup from remote mongodb instances also. I have a lot of MongoDB databases for my personal projects on MongoDB atlas, which is the free to use Cloud database for MongoDB. To get a backup of remote databases, we have to use the connection string with –uri parameter. I used the below command. mongodump --uri "mongodb+srv://xxxx:xxxxxxxxxxx@cluster0.suvl2.mongodb.net/xxxxxDB?retryWrites=true&w=majority" --out C:\Users\pc\Desktop\Backup You can see in the below output the backup of the remote instance. MongoDB Backup procedures We should try to make the backup procedure as automated as possible. One of the best ways is to use a cron job, so that it can run every day. As, discussed earlier it is best to run the backup in the night when the database has the least load.  Setting up a cron job is easier on a Linux or a Mac because the Windows equivalent of it is not good. Alternatively, you can do install mongodb in WSL2 for Windows which supports Ubuntu.  Suppose, on a Linux host which has a mongoDB instance running, you want to run the backup at 04:04 am daily. For this in the terminal, open the cron editor by running the below command in the terminal. sudo crontab –e Now, in the cron editor, you need to add a command like below for our case. 4 4 * * * mongodump --out /var/backups/mongobackups/`date +"%m-%d-%y"`Restoring and migrating a MongoDB database When we restore the MongoDB database from a backup, we will be able to take the exact copy of the MongoDB information, including the indexes. We restore MongoDB by using the command mongorestore, which works only with the binary backup produced by mongodump. Now, we have taken the backup of example database earlier and it is in our Backup folder. We will use the below command to restore it. In the arguments we will specify the name of the database first with –db option. After that with –drop, we make sure that the example database is first dropped. And in the final argument, we specify the path of our backup. mongorestore --db example --drop C:\Users\pc\Desktop\Backup\example Now, if we check in terminal, we have our example database restored properly. Conclusion In this article, we have learned about MongoDB backup and restore. We have learned the different options for the backups, and why and when backups are required. Keep learning! 
5626
Back Up, Restore, and Migrate a MongoDB Database

Popular among both enterprises and startups, Mong... Read More

What’s New in Leading SAFe® 5.0

The global SAFe® summit, organized by Scaled Agile Inc. has declared a new variant of the Scaled Agile Framework. The new, simplified version of the model features business activity, focusing on providing a positive customer experience and expanding the critical aspect of portfolio management. SAFe® has added more clarity, structure, and direction. This post attempts to provide an overview of some major changes in SAFe® 5.0.  This new release is intended to extend SAFe® to encompass the complete enterprise and enable improved business activity. This post attempts to provide an overview of some major changes in SAFe® 5.0.  Important Highlights of SAFe® update  Gives the big picture for better features, flow, and continuous delivery   Developing value streams patterns supports model around the request from customers  Applying SAFe® to hardware improvement accelerates the delivery of cyber-physical systems  New direction and guidance around DevOps technical skills and tools for continuous delivery pipeline  More comprehensive direction for implementing Lean-Agile methods to business domains supports business agility  Integrated participatory budgeting promotes a dynamic and collaborative method of allocating funding to value streams  New designs, patterns, and behaviors for teams and ARTs simplifies their values  Incremental updates to SAFe® 5 will guarantee it stays current with new and evolving business and technology trends.WHAT’S NEW? Below are the highlights of what’s new in SAFe® 5.0. Customer focus in SAFe® 5.0 One of the primary changes is to focus on a customer-centric approach. Version SAFe® 5.0’s motto is to give a satisfactory experience to the customer. SAFe® recommends focusing more on what the customer is getting from the business and helps them focus on decision-making. The most important ingredient is revamped core competency, which focuses on understanding the needs of customers, setting customer lifetime value, and then building products that are customer-centric. New Big Picture The below graphic incorporates the contents of SAFe®, comprising a sketch of-- Essential SAFe®, Large Solution SAFe®, Portfolio SAFe®, and Full SAFe® and the consolidated updatesSource LinkConcentrate/ Focus on Business Agility.  Business Agility is the ability to face and grow by immediately responding to buoyant market conditions, varying customer needs, and emerging technologies. It requires that everyone is committed to delivering solutions—business and technology leaders, development, IT operations, legal, marketing, finance, support, compliance, security, and others—use Lean and Agile applications to continuously deliver innovative, high-quality products and services quicker. It is the differentiator that will determine the winners and failures in the digital economy. SAFe® defines business agility as “The capacity to compete and succeed in the digital age by reacting quickly to market fluctuations and opportunities with innovative business resolutions. It expects all those concerned in furnishing solutions i.e. business and technology leaders, development, IT policies and procedures, law, marketing, finance, maintenance and support, compliance, security/ protection from hackers, and others – to apply lean and agile methods to continuously provide innovative, quality products and services quicker than the competition.” How will business agility solve the problem? Enterprises start as a customer-centric network. As the organization progresses, the entrepreneurial network moves adjacent to the newly constituted “hierarchical arrangement” which is anticipated for the organization to mature. As the hierarchy grows to accomplish the organization’s revenue and growth needs, it begins to clash with the entrepreneurial network, which leads to network failure and customer-centricity getting lost in between. Nonetheless, this allows organizations to develop, but if a change in technology or customer requirement arises, companies fail to react and change. Instead of discarding the current system, a secondary system “SAFe® 5.0 Business Agility” could be executed which allows concentrating more on formulating value streams, not just departments. New SAFe® Overview SAFe®'s seven center capabilities encourage business readiness. The visual underneath shows an unmistakable image of SAFe®'s Seven Core Competencies of the Lean Enterprise and furthermore shows their 21 measurements that assist business readiness.   Execution competencies are displayed on the left, while the support strategy competencies are on the right. The Agile-Lean Leadership competency which is the foundation is in the bottom middle. The customer is prominently emphasized in the middle as the focal feature for all the competencies. Measure and Grow at the top right is a suggestion of the importance of cyclic self-assessments to track the organization’s journey towards the principles and practices that facilitate business agility.  Source LinkMeasuring Business Agility The SAFe® framework now includes Business Agility Assessment that empowers organizations to estimate their level of business agility and get support on expediting growth. The assessment incorporates the ratings of organizations according to various standards and levels within each core competency. Outcomes from this evaluation, represented by the radar below, can be represented as a baseline. As such, these can support organizations to determine the current status and know which fields to concentrate on for enhanced growth. It can help to prioritize for maximum accomplishment on the path to business agility. TWO NEW COMPETENCIES SAFe® 5.0 acquaints us with two new abilities-- Continuous Learning Culture, and Organizational Agility. Both of the skills are depicted in detail below. Continuous Learning Culture   The Learning Culture competency outlines a set of values and methods that inspire people and the complete organization to upgrade knowledge, skill, performance, and innovation. The aforementioned culture is achieved by encouraging the organization to upgrade knowledge, executing constant improvement, and promoting a culture of innovation.   The image below outlines the three dimensions of a continuous learning culture:Learning Organization – Employees would desire to upgrade themselves at each level and therefore the organization transforms and can endure an ever-changing world.  Innovation Culture – Employees are encouraged and empowered to explore and accomplish original concepts that expedite future value delivery.  Constant Improvement – Every part of the enterprise concentrates on continuously enhancing its solutions, products, and methods. Organizational Agility  The Agility competency of an Organization defines how Lean-thinking and Agile teams optimize their business processes, amplify the approach with clear and definitive new consignments, and immediately benefit the organization as expected to capitalize on new possibilities and opportunities. This new article explains the three dimensions of organizational agility:  Lean and Agile Teams – Teams that are connected with solution delivery are trained in Lean and Agile systems and know how to adopt and exemplify the values, policies, and practices.   Lean operations business team – Teams follow Lean principles to concede, map and continuously improve the business systems that support the business products and services.   Strategy Flexibility – The enterprise is manageable and flexible enough to continuously sense the market, and immediately adjust tactics when required.FIVE COMPETENCIES RESTRUCTURED Team and Technical Agility  The Technical Agility team outlines the Lean-Agile principles and methods that high-performing Agile teams use to provide high-quality resolutions for customers. The outcome is improved productivity, more stability, quality, faster time-to-market, and quick anticipated delivery of value. This competency has been written and is classified into the following dimensions: Agile TeamsHigh Performance of the cross-functional teams ensures competency by employing efficient Agile principles and practices.Agile Unit TeamsAgile teams function within the context of a SAFe® Agile Release Train (ART), a long-lasting, team of Agile teams that bestows a shared insight and direction and is ultimately accountable for delivering solutions.  Built-in QualityAgile teams execute Agile iterations to provide high-quality, well-designed recommendations that help current and prospective business requirements.Agile Product Delivery  Agile Product Delivery is a customer-centric approach to determine, develop, and deliver a constant stream of products and services that are of value to customers and users. This supports the organization to provide solutions that delight customers, reduce development costs/ risk, and reduce competition.  DevOps and Release competency has been combined into a couple of dimensions of Agile Product Delivery as shown in the Figure below:Customer-centric Thinking – Customer centricity puts the customer at a locus and uses design reasoning to ensure that the resolution implemented will be useful, possible, achievable, and can sustain in any circumstances.  Acquire on-demand and Declare on Request– Developing on flow enhances control in product development.  Releasing the value engagements to customers in segments would help customers to satisfy their requirements.  DevOps and the Continuous Delivery – DevOps and the Continuous Delivery Pipeline create the foundation that assists organizations to deliver excellence, in cumulative parts or in segments, at any point to satisfy consumer and market requirements. Lean Portfolio Management  The Lean Portfolio Management aligns strategies and achievements by implementing Lean methods approaches/ strategies, Agile portfolio methods, and governance. These collaborations deliver organizations the expertise to meet existing commitments and enable innovation.This competency has been revised and is classified into the following dimensions:Strategy & Investment Funding ensures the entire portfolio is aligned and financed to formulate and support the solutions expected to adhere to business targets.    Agile Portfolio Operations encourage decentralized program performance and promote operational excellence.    Lean Governance accommodates decision-making of spending, auditing, forecasting engagements, and measurement.Organization Solution Delivery  The Organization Solution Delivery competency shows how to apply Lean-Agile principles and methods to product specification, expansion, deployment, accomplishment, and progress of advanced software applications, networks, etc The Business and Lean Engineering Systems competency has been renamed as Enterprise Solution Delivery and it incorporates the following dimensions: Lean Solution and Systems   Engineering applies Lean-Agile practices to manage and coordinate all the activities needed to execute, test, deploy, evolve, and sequentially decommission these systems.   Coordinating Suppliers   Suppliers are coordinated and aligned to a set of value streams. This uses coordinated vision, backlogs, and roadmaps with common program Increment points.   Continually Evolve Live Systems assure large systems, and their growing pipeline supports continuous delivery. Lean-Agile Leadership  The Lean-Agile Leadership competency specifies how Lean-Agile Leaders manage and maintain organizational change by empowering individuals and teams to reach their highest potential. Adopting a Lean-Agile mindset results in more engaged employees, increased productivity and innovation, and successful organizational change.  The Lean-Agile leadership was revised and is grouped into the following dimensions:Set by example – Leaders achieve earned prestige by inspiring the team to incorporate the leader’s example into their own personal development journey.  Principles and Mindset – Embedding the Lean-Agile approach of working in their ideas, choices, acknowledgments, and activities, leaders model the required norm throughout the organization.  Managing Change – Leaders lead the transformation by designing the environment, preparing the people, and providing the necessary resources to realize the aspired outcomes. CUSTOMER FOCUSED DESIGN THINKING The Customer Centricity mindset has extended its focus to the mechanisms and systems that are aimed at resolving issues that customers face.  Customer Centricity The customer-centric organization conducts market research to create actionable items of the problems that customers face, the solution specifications, and the solutions required to resolve issues. FOR BUSINESS TEAMS SAFe®  Team of teams in SAFe® acts as an agile release train and it presents value to the organization. They adopt the Lean and Agile values, principles, and practices that are relevant to their responsibilities and adjust their existing processes accordingly. The Agile Release Train (ART) is a long-lived team of Agile teams, which, accompanied by different stakeholders, incrementally develops, delivers, and where applicable operates one or more solutions in a value stream. ARTs comprise cross-functional teams and possess all the abilities—software, hardware, firmware, and others—needed to define, implement, test, deploy, release, and where applicable, operate solutions.ARTs operate on a set of common principles:  If a Feature misses a timed departure and is not planned in the current PI, it can be taken in the next one.  Each train delivers a new increment every two weeks.  Teams on the train are synchronized on the related PI of 8 – 12 weeks and have common Iteration start/end dates and duration.  Each ART estimates how much can be delivered in a PI.  Agile Teams welcome the ‘Agile Manifesto’ and SAFe® Core Values and Principles. They apply Scrum, Extreme Programming (XP), Kanban, etc Built-In Quality practices.  Most people in ART are committed full-time to the train. The ART plans work periodically mostly face-to-face PI Planning events.  An Inspect and Adapt event is held at the end of every PI.  Teams and management identify backlog items via a structured, problem-solving workshop.  ARTs apply flow and synchronization to better accomplish the internal variability of investigation and improvement.  NEW SAFE® IMPLEMENTATION ROADMAP The Scaled Agile Framework for enterprises contributes integrated, well established scaling patterns that have benefited many organizations around the world to solve their business obstacles associated with speed, multiple teams' alignment, flexibility & quality, and improvement with successful Agile delivery.    The SAFe® Roadmap outlines the levels of the organization and implements SAFe® in an arranged, stable, and successful fashion. While adopting SAFe® would vary based on circumstances, the Implementation Roadmap offers insight into a fairly common implementation pattern. The roadmap has been developed by proven change management strategies and the experience of hundreds of global enterprises that have adopted SAFe®.   The SAFe® Implementation Roadmap includes 12 critical moves for the successful embracing of Lean-Agile principles and mindset and their applicability throughout the organization.WHAT ARE THE CHANGES FROM 4.5 TO 5.0  Below are the diverse levels in SAFe® 4.5 and SAFe® 5.0. SAFe®  5.0 Level  SAFe® 5.0 is the most advanced level that comes with an important update to the last version 4.5. It comes with two extra competencies i.e. Lean Enterprise and Business Agility. SAFe® 5.0 with extra two competencies also focuses on core competencies of SAFe® 4.5 that includes Technical and Team Agility, Release on Demand and DevOps, Lean Systems Engineering and Business Solutions, Lean Portfolio and Lean-Agile Leadership.  SAFe®  4.5 Level Four levels are incorporated in this SAFe® implementation-- they are Portfolio, Value Stream, Program, and Team. It is mainly used for resolutions that require several professionals to create, deploy, manage and maintain softwareWHAT DOES VERSION 5.0 IMPLY Scaled Agile Framework inspires realization within organizations that there is a need to transform development teams. They require to transform organization-wide in order to compete in today’s landscape. The focus has now whirled towards full business agility. In reference to SAFe® 5.0, Business Agility empowers organizations to capitalize on rising opportunities by allowing people to make quick settlements, designate money, and adjust the right people to work.  SAFe® confirms that a framework alone is not sufficient to achieve a successful transformation; the true difference makers are the talent i.e., leaders and teams of the organization. Globalization, fast-moving markets and the unprecedented pace of technological innovation provokes organizations to transform to survive. But their current business models, organizational hierarchy, and technology infrastructure often hold back organizations from transforming fast.  Important Highlights of SAFe® 5.0:  Focus on customer centricity and design thinking empowers the organization to recognize the problem and design the right solution.  New Measures and guidance help the organization circumscribe its current state of business agility and recognize tactical steps to enhance economic outcomes and reach its desired state.  Continuous Learning Culture competency provides a collection of values and practices that inspires everyone in the enterprise to continuously learn and innovate with mutual cooperation.  Organizational Agility helps teams optimize their enterprise processes, develop strategies with clear commitments and quickly accommodate to realize new opportunities.  SAFe® 5.0 allows teams to engage in delivering and supporting innovative business resolutions.  It organizes and helps enterprise regulate their development efforts around the full, end-to-end value flow. CONCLUSIONSAFe® 5.0 brings the significant modifications that were required for organizations to improve but also not lose core focus on customers. With business agility, organizations can now concentrate on generating value streams for their overall maturity and growth rather than focus on each department individually. The two new core competencies will empower the organizations to generate a learning culture to encourage continuous improvement in innovative solutions, performance, and growth and also modify or accommodate artifices according to the variation in market trends. Overall, it helps in bringing back the focus without losing it in the hierarchical structure of organizations.
7318
What’s New in Leading SAFe® 5.0

The global SAFe® summit, organized by Scaled Ag... Read More

How To Work With Forms in React

Forms are a crucial part of React web applications. They allow users to enter and upload information directly in components from a login screen to a checkout page. As the majority of React applications are single-page apps or web apps that load one page dynamically displaying new information, you will not send the information to a server directly from the form. You will instead capture and submit or show the information in the form on the client-side using an additional JavaScript file. React forms are unique because either you can allow the browser to process and collect data through React Change Events, or you can use React to completely manage this feature by setting and modifying its input value directly. React formats are unique because they can be reused. The first approach is an unregulated component because React does not set the value. The second approach is a controlled component, since React updates the inputs actively. Handling Forms Form handling is an important part of a wide variety of internet applications and React is one of the best way to handle forms. You have plenty of flexibility to regulate and enforce these controls and there are many ways to accomplish the same. Adding Forms in React HTML form components function a little differently than the other DOM components, as form components naturally hold some internal status. When the user submits the form, the Form is the default HTML form browsing activity for a new page. In react, it works only if you want this behaviour. In most cases, however, it is advisable to have a JavaScript function which handles the form submission and has access to the form's user data. A technique called 'controlled components' is the traditional way to do this.Controlled Components A controlled component is bound to a value, and its adjustments will be handled in code by using event-based callbacks. Here, the input form variable is handled by the react itself rather than the DOM. In this case, the mutable state is maintained in the state property and modified using setState(). Controlled components have functions which regulate the data that occurs at each on Change event. This data is subsequently saved in the setState() method and updated. It helps components manage the elements and data of the form easier. The controlled component is a way you can handle the form input via state. If you are using React Hooks, you can change the form input value by just one way and when the user begins writing some setState or useState characters, this state can be called and you can update it through one event like on Change. You can use the controlled component when you create: Forms validation so that when you type, you always have to know the input value to verify whether it is true or not! Disable submission icon, except for valid data in all fields If you have a format such as the input for a credit card. Conditional Rendering You can create dynamic, highly interactive single-page applications (SPAs). The conditional rendering is one function that enables this. Conditional rendering is a concept that defines how various user interface markups can be rendered if a condition is true or false. In response, it enables us to make various elements or components dependent on a condition. In the following scenarios this concept is used: External API data rendering Elements may be shown or hidden The functionality of the toggling application Permit level implementation Authentication and approval management. Submitting Forms Our new item has additional features, so we have to add additional fields to accommodate these features. We also need to establish a feature to fire the form and transmit information to the remote collection so that it can also be applied. To call handleSubmit, we must add it to the onSubmit prop on the form. OnSubmit watches and invokes the features to which we transfer them for the form submits.handleFormSubmit = (event) => {    console.log(this.state.name)    event.preventDefault();  };  render() {    return (              Name:                Send          );  } Multiple Input Fields It is normal to use an onChange handler to listen to changes in the input elements and save their values to form when building a form using react components. A single onChange handler can be configured to manage several different inputs in the form, in addition to managing just one input. render() {    const colors = ['Blue', 'Red', 'Green', 'Yellow'];    const sizes = ['Small', 'Medium', 'Large', 'XL', 'XXL', '3XL'];    return (                                    Name:                                            Observation:                                            Desired color:                          {colors.map((color, i) => {color})}                                            T-shirt Size:            {sizes.map((size, i) =>                              {size}                                          )}                                              I accept the agreement                                                      );  } Validating Form Input The form must also be able to accept values so that both a development and an edit flow can be used. Since both forms of validation wish to use the same form component, the State and validation logic shall be lifted to a parent component to carry out the validation.  Example:    We have just added a required input feature. In case an empty and valid field has at least one character, the browser will find this input field invalid. If the input fields are at least invalid, the browser will not allow the user to send the form. Adding Error MessageTo show input error feedback we need to transfer the affected and correct properties to its component as a prop for that particular input. Based on the valid state, we will add the error style. We need to update our component file. import React from 'react';  const TextInput = props => { let formControl = "form-control"; if (props.touched && !props.valid) { formControl = 'form-control control-error';     } return (   ); } export default TextInput; The textarea TagTextarea, which is used to get multi-line feedback from the user, is a popular form control. It’s different from a standard text entry that only allows one-line input. An address field is a clear example of a Textarea use case. Example: export default class App extends Component {    state = { bio: '' };      handleBioChange = (e) => {      const bio = e.target.value;      this.setState({ bio });    };      render() {      return (                  Bio:                        );    }  } The select Tag Select in HTML helps us to use the dropdown for choosing among many values. Here we are addressing adjusting selected choices based on a particular dropdown. In React, with the aid of the State it is very simple to achieve. It’s a brief for those who don’t care about state. render() {    return (              Desired color:                            Blue          Red          Green          Yellow                  );  } The file input Tag In HTML, the user can upload or manipulate one or more files of the device’s storage via the File API via JavaScript.  We generate a component of FileUpload and save the file object. We get the uploaded picture file via event.target, update the component status, and show the picture and information. Handling Multiple Inputs You can add a name attribute to each item when you need to handle several managed input items. function useFormFields(initialValues: T) {    const [formFields, setFormFields] = React.useState(initialValues);    const createChangeHandler = (key: keyof T) => (      e: React.ChangeEvent,    ) => {      const value = e.target.value;      setFormFields((prev: T) => ({ ...prev, [key]: value }));    };    return { formFields, createChangeHandler };  }    export function LoginForm() {    const { formFields, createChangeHandler } = useFormFields({      email: "",      password: "",    }); Controlled Input Null Value The value change of a controlled component prevents the user from adjusting the input unless you wish to. You can accidentally set the value as undefined or null if you have specified a value, but the input is still editable. class ControlledInput extends React.Component {    constructor(props) {      super(props);      this.state = { name: '' };      this.handleInput = this.handleInput.bind(this);    }      handleInput(event) {      this.setState({        name: event.target.value      });    }      render() {      return (              );    }  } Alternatives to Controlled Components It is often tedious to use controlled components, because for every manner in which your data modifies and pipes the entire input state using a React component, you will need to create an Event Handler.  export function LoginForm() {    const handleSubmit = (e: React.FormEvent) => {      e.preventDefault();      const formData = new FormData(e.target as HTMLFormElement);      api.login(formData.get('email'), formData.get('password'));    };    return (                        Email                           Perhaps you found that in the handleSubmit function we are doing something new. We use an integrated FormData browser API. FormData is a convenient way to get field values from our fields of input! Creating a Basic Form with JSX With a single element and a submit button using JSX, you are going to generate an empty form. You will manage the form and transfer the information to another service. import React from 'react';  import './App.css';  function App() {    return(              How About Them Apples                                        Name                                          Submit                  )  }  export default App; Collecting Form Data Using Uncontrolled Components In this stage, uncontrolled components will be used to collect form data. An uncontrolled component is a component with no response meaning. You can bind to the onChange event to collect the user feedback instead of setting the data on the component. You can learn how the react handles various types of input and how you construct a reusable feature for collecting form data into a single object as you develop the components. import React, { useReducer, useState } from 'react';  import './App.css';  const formReducer = (state, event) => {   return {     ...state,     [event.name]: event.value   }  }  function App() {    const [formData, setFormData] = useReducer(formReducer, {});    const [submitting, setSubmitting] = useState(false);      const handleSubmit = event => {      event.preventDefault();      setSubmitting(true);        setTimeout(() => {        setSubmitting(false);      }, 3000);    }      const handleChange = event => {      setFormData({        name: event.target.name,        value: event.target.value,      });    }      return(              How About Them Apples        {submitting &&          Submtting Form...        }                                            Name                                              Submit                  )  }  export default App; Updating Form Data Using Controlled Components You’ll set up and update your data dynamically with controlled components in this phase. To set or update the form data, you can add a value prop for each variable. The form data will also be reset on the submit. ...    return(              How About Them Apples        {submitting &&                      You are submitting the following:                          {Object.entries(formData).map(([name, value]) => (                {name}: {value.toString()}              ))}                              }                                            Name                                                                        Apples                                --Please choose an option--                  Fuji                  Jonathan                  Honey Crisp                                                    Count                                                    Gift Wrap                                              Submit                  )  }    export default App; Dynamically Updating Form Properties You will update the form element properties dynamically in this process. During the submission, you can set the property to previous choices to avoid unintended submissions and disable your form. Every part is currently static. It does not shift with the shape changing. Forms are complex in many applications. Based on previous data, fields can change, justify and reveal mistakes. Fields may disappear or grow as other components are filled. Like most React components, the components and attributes can be dynamically defined and re-rendered with changes in data. Fully-Fledged Solutions Formik is one of the most common options if you’re looking for a full solution, including validation, monitoring of the fields visited, and submitting a handling form. However, it is based on the same controlled components and state management principles—so it is important to get to know them. Conclusion In-depth knowledge of forms is important for rich Web apps. In React, you have different options for forms and elements to be connected and regulated. You can upgrade properties, including the value input elements, dynamically like other components. The best way of simplifying unchecked components is to clean them or trigger them with data, but they may not be appropriate circumstances. You can also change data by using controlled components, but can add another abstraction level which can trigger unintended bugs or re-renders. Whatever your approach, React allows you to upgrade and adjust your forms dynamically to your application and user requirements.
5626
How To Work With Forms in React

Forms are a crucial part of React web application... Read More