Categories
- All165
- UX12
- Web Technology63
- Ecommerce8
- Mobile14
- Business Practices16
- Subscribe

Creating forms in React – The Right Way!
In the world of web development, there are several front-end frameworks. Angular, Vue, React and a few others have gained immense popularity over the last few years. However, React has surpassed other frameworks in terms of popularity and demand:
React is used to build single-page applications and allows the creation of reusable UI components. Forms are an important component of React applications. They facilitate users’ interaction with the application. Some of the common use cases of forms are:
- Login and Registration Forms
- Contact Form
- Checkout Forms
- Create/Edit Order Forms
- Adding or updating data into the application
It is virtually impossible to develop a React-based app without forms. At the very least, you will need it for the login and sign up screen, in case the data is retrieved.
In this article, we will share some best practices for creating forms in React. Let’s get started.
Forms using Controlled Components
We know that HTML elements like input remember what we type. Similarly, we can use the React component state to store data of forms. When the input data of forms elements is handled by the React component, it’s called a Controlled Component. Here, the only source of truth is a component state, not a DOM element.
Handling Forms
This describes how the data is handled when the value is changed or submitted. In HTML, the form data is usually handled by the DOM whereas, in React, components are used. When the data is handled by the components, it is stored in the component state.
Here is the code –
This is how one can collect the data from the user and get it right there in the React.
In the same way, if one wants to update the state, one can use the event handler “onChange”.
Now, to execute it, one can use the following code.
Conditional Rendering
If you do not want to display the h1 element until the user has made any input, you can add an if statement. Look at the example below and note the following:
1. Create an empty variable, in this example call it a header.
2. Add an if statement to insert content to the header variable if the user has done any input.
3. Insert the header variable in the output, using curly brackets.
Multiple Input Fields
You can control the values of more than one input field by adding a name attribute to each element. Here is how you can achieve this
- When you initialize the state in the constructor, use the field names.
- To access the fields in the event handler use the event.target.name and event.target.value syntax.
- To update the state in the this.setState method, use square brackets [bracket notation] around the property name.
Validating Form Input
You can validate form input when the user is typing or you can wait until the form gets submitted.
Adding Error Message
Error messages in alert boxes can be a tad bit annoying! We recommend displaying the error when the user input is invalid.
Using React Hooks – Alternate Method
We can also handle the form state using React hooks. To do that we have useState() hook for storing state in a functional component. Let me explain this by creating a simple form with one input element and handle its data using a hook.
import React, { useState } from ‘react’; export default function ControlledFormWithHook() { const [name, setName] = useState(”); return ( <div> <form> <label>Name:</label> <input type=”text” onChange={(e) => setName(e.target.value)} /> </form> <br /> Name is: {name} </div> ); } |
Here we have used a useState() hook to handle state.
Why use React-hooks-form?
One of the primary goals of React Hook Form is to reduce the amount of code that you have to write. As you can see from our final result, the React hooks form is elementary to use, and it takes a small amount of code.
Making The Right Choice
Forms are a crucial part of most web applications. It is imperative to know how to handle them, and fortunately, React provides a lot of ways to do just that.
For simple forms that don’t require heavy validations (or that can rely on HTML5 form validation controls), you can use the built-in state handling of the DOM given to us by default. There are quite a few things you can’t do (like programmatically changing the input values or live validation), but for the most straightforward cases (like a search field or a login field like above), you’ll probably get away with an alternative approach.
When you’re doing custom validation or need to access some form data before you submit the form, handling the state explicitly with controlled components is what you want. You can use regular useStateHooks, or build a custom Hook solution to simplify your code a bit.
Whatever you decide to use, handling forms in React has never been more straightforward than it is today. You can let the browser handle the simple forms while handling the state explicitly when the situation requires it. Either way – you’ll get the job done in fewer lines of code.
Contact Us right away to discuss your website or app development according to your business requirement and complexities.
About Galaxy Weblinks
We specialize in delivering end-to-end software design & development services and have hands-on experience with large, medium, and startup business development requirements. Our engineers also help in improving security, reliability, and features to make sure your business application scale and remain secure.
By Admin
About Galaxy Weblinks
We specialize in human-centric user experience design services to our clients across the globe. Our innovative ideas, creative designs, industry best practices, and processes help us improve user satisfaction and solve complex design problems. Contact us for a free consultation!Related Posts

7 Best Practices For React Security
React is undoubtedly one of the most popular JS libraries to build applications. It is also one of the most actively...

5 Tools For Efficiently Managing Technical Debt
In our previous article, we talked about what is technical debt and how one strikes a balance between juggling code ...

Managing And Minimizing Your Technical Debt
Technical Debt - also known as Code Debt, Design Debt, or Tech Debt is often the byproduct of speedy deliveries of t...

Micro Frontend | 4 Things to know before switching
The first part of this series uncovered the idea of Micro Frontends that is to break down the frontend monolith into...

Micro Frontends – A Nimble Approach Towar...
This is a two-parter series on Micro-Frontend and it's implementation. And if you've already read this one, head on ...

How to Migrate to .Net 5 without any hassles?
As 2020 came to an end, Microsoft announced their .Net 5 release along with a fixed schedule for release and support...

Craft CMS: Building the frontend of a website u...
Craft is a mature and tested content management system. Airbnb, W3C, Netflix, PBS, Salesforce, Moz, and countles...

GWL 2020 Wrapped: Top 10 Blogs You Must Read fo...
At Galaxy Weblinks, we build high-performing software solutions that help teams scale. And write about it in the pro...

Best Frontend Development Frameworks for 2021
For the past few years, Frontend developers have shown partiality towards React, with Vue.js and Angular tagging beh...

A brief overview of the React 17
First things first, yes there are no new features in this update! There are several upgrades and a few eliminations ...

Migration Plan To The All New Vue JS 3
Vue 3 is here and everyone is looking forward to catching up with the upgrade ASAP. Vue JS is the best client-sid...

Why you should partner with a development agency?
As a creative agency, it is imperative for you that your product is developed exactly as you envisioned without count...

What is Node.js and other things you should kno...
Whether you have recently started learning Node.js or thinking about using it in your next project, this blog will he...

Migrating your Legacy Apps to Cloud
Cloud usage has increased by many folds over the past few years. Public clouds have become the goto choice of enterpr...

Atom vs Sublime: Which text editor to choose in...
Developers use Text Editors, also known as code editors, for editing programming code. These editors basically contai...

Why it is better to partner with a Digital Agen...
Your business is growing and your team is doing their best to meet the tight deadlines and increased workload. You ma...

Why should you consider a Single Page Applicati...
Single Page Applications(SPAs) are all around us. Industry leaders like Google, Trello, Facebook, Gmail, Github, vouc...

Next JS or Electron | Which Way to Go?
When we talk of Next JS, server- side rendering is the first thing that comes to our mind. On the other hand, Electro...

5 ways to optimize your ecommerce website for V...
Voice search is at its peak in popularity among millions of users. According to an OC&C Strategy Consultants mark...

Performance changes that we might see in Angula...
Even though there is no word on Angular 10’s release and to be honest it’s too early to expect a release, the develop...

A failproof Magento 2 migration plan
Editor’s note: If you are still wondering ‘Do I really need to upgrade to Magento 2’, we recommend reading our 5 reas...

Is Hyper-Personalization the key to your E-comm...
Hello (Inserts your First name), All of us have received emails/ sms notifications, social media ads, that are sha...

WordPress 5.4 ‘Adderley’ | New feat...
The recently released WordPress 5.4 ‘Adderley’ update has got a lot to look forward to! Since this highly popular CMS...

9 web app development frameworks that continue ...
App development frameworks are at the front and center of the development community. Backend and frontend frameworks ...

Why Design QA should be a non-negotiable part o...
Did you ever happen to spot some inconsistencies in your product’s design that were not there in your prototype? The ...

Redesigning lessons from Super Bowl
About 100 million people tune into Super Bowl every year. The game is big because the money is big. Companies spend a...

Personalization | Key to E-commerce success
With most shopping happening online, the consumer purchasing behaviour has seen a paradigm shift. Earlier the options...

Why should you outsource Digital Production?
When everybody is fighting for online presence and consumer's limited attention, quality and scale of digital assets ...

Gutenberg vs Page builders | Settling an year l...
The appeal of WordPress is simplicity. The debate on Gutenberg and Page builders is much more than functionalities. I...

Making web more inclusive with Manual Accessibi...
People don't want to miss out on the digital era. And accessibility testing is how we make sure that smart devices an...

6 factors to consider before choosing your e-co...
Setting up a shop online? Well it's easier than setting one up made of bricks and mortar. But it doesn't mean that...

Vue or React | Which Javascript framework shoul...
The pursuit for finding the perfect “javascript framework” can seem like a wild goose chase. But it never is. There a...

Tips To Remember While Designing a Website
In the world of online business and marketing, website plays an important role. Website signifies the online presence...

Why it’s a bad idea to ignore older adult...
Modern technology has two problems: Devices have too many integrated features and everything is smaller. A good im...

iOS 13 design | What’s changed and what remains?
Ever wondered why Apple allows only selected employees in its Industrial Design Studio? Surprisingly, it’s a part ...

Unboxing popular PWAs | Techniques used and impact
What is common between Pinterest, Tinder, Uber, Trivago, and Airbnb? All these companies experienced a surge in th...

Kotlin 1.3.50 | More than just a performance up...
Kotlin has emerged as both substitute and supplement to C++ and Java. In 2018, the language had over 96,000 repositor...

Galaxy Weblinks Ranked Among Best Web Developer...
When you think of hotspots for tech, don’t zero in on Silicon Valley just yet. According to Expert Market, Boston ...

Product tour lessons from Disneyland | What kee...
The experience of Disneyland is always an awe-inspiring one. No matter how many miles you have walked, you are always...

What are Google Play’s new mobile app requireme...
Google Play set out many criteria in their app guidelines that you need to follow. These changes may cause some issue...

Turning remote collaboration challenges into op...
Leading the AR revolution, industrial enterprises are experiencing improved ROI through AR-optimized supply chain. En...

The flip side of Wellness apps
Contrary to popular belief wellness apps are not so wholesome after all. Apart from the flaw in fundamental defini...

The Bare Bones of Skeleton Screens
Losing customers to Slowpoke of a UI is a nightmare for any UX designer. What if there was a pseudo-catalyst that cou...

What is Code Readability?
You are a programmer when you write code. You are a brilliant programmer when you write readable code other programme...

All there’s to know about the new Swift U...
Apple in its annual WWDC made some game changing announcements like a new Mac Pro, an exclusive OS for iPad, iOS 13 r...

Prototyping | Our playground for Idea Validation
Prototyping might slow down the design process but it fast tracks the entire product development process. Our team...

You ARen’t collaborating remotely even if...
Fun fact: Virtual reality was realized way before digital computing was even a thing. Virtual reality came into ex...

Galaxy Weblinks on Clutch 2019 List!
As Galaxy Weblinks says “Our first and most important job: to help our clients understand the totality of the technol...

Making your UX more human with digital wellbeing
A wellbeing app called ‘Calm’ was recently valued at a sizeable billion dollars. This billion dollar app is a meditat...

What Configuration management gets right spotti...
At the time of an unsuccessful product deployment, you might ask yourself. “What went wrong with the product deliv...

Choosing the right QA tool for your organization
Selecting the right QA tool from a list of the most popular ones is difficult. Your operational scope defines your te...

How to conduct a mobile usability test?
It is important to know that there are more variables when it comes to recording mobile usability test. The technical...

Outsourcing QA | A Doomsday prepper’s guide to ...
You might be familiar with Murphy’s law which says ‘Anything that can go wrong, will go wrong’. Software isn’t immune...

Scala v/s Java | Approach & performance ove...
Scala is a derivative of Java, but comparisons can't be avoided. These languages share similarities to some extent an...

Mastering the Art of Data Driven Web Designing
The web traffic is constantly growing and designers struggle to create and maintain website which is optimized to r...

Is WordPress 5.0 headed the Craft CMS way with ...
When you look at the respective market share of both the CMSs, WordPress has a clear edge over Craft CMS with 81.9% m...

Angular 7 upgrade | What will you miss if you i...
Angular 6, released earlier in May 2018 didn’t offer much improvements on the performance part. It was mainly focused...

Developing Custom Softwares, the Agile Way
The dynamic business environment with rapid technological changes have resulted in subsequent changes in customer re...

Craft & its Plugins | A transforming workflow
We like to think of Craft CMS as a Transformer (one with BumbleBee as his friend) and plugins as its Jet Pack. And ev...

How we use Zeplin for an Agile workflow
Earlier when our designers completed the wireframe of a project, they worried about the design handoff and the tediou...

Drupal 8.6 update. What’s new?
Keeping up with the promises made during earlier announcements, Drupal released the 8.6 version on September 5. The u...

Magento 1 End Of Life: It’s time to migrate to ...
Magento announced that it is pulling the plug on Magento 1 in April 2017 at the ‘Meet Magento’ conference in Prague. ...

ACF vs Visual Composer website builder: Which i...
Building a Wordpress website? The Wordpress community provides you with plenty of options. You can either make ...

WhatsApp Business API: What’s in the limited pu...
Facebook has finally decided to monetize WhatsApp. Earlier this month, on August 1, Facebook rolled its long-in-de...

How to use Macros with Twig in Craft CMS — DRY
Templating is one of the most commonly used processes in web development. It helps with easier management during the ...

Craft Vs Perch: A Clash Of Customizable CMSs
In our earlier blogs we’ve favoured Craft CMS heavily because of its ‘content first’ philosophy. Perch also majorly f...

How to migrate a Craft 2 project to Craft 3?
Craft 3 update changed a lot of things. Added functionalities aside, the process of installing and maintaining the CM...

More Craft CMS Features: Matrix and Its Powerfu...
Craft CMS’s consistency can be seen in its regular updates & latest features. Matrix is one of those early featur...

Debug Tool in Craft 3: Here’s all you need to k...
Before introducing the Debug Tool in Craft 3, Craft CMS made you install a separate web-based application, Web-Consol...

How to Setup a New Project in Craft CMS 3
There are two ways you can set up a new project in Craft 3, vis-a-vis, via Composer and Manual. Both the methods requ...

How To Get Started With SEO In Craft CMS
SEO in Craft CMS is easy and quick. Craft CMS offers several SEO options depending on the approach you choose. You ca...

How To Create A Content Builder In Craft CMS
It is easy to create a content builder in Craft CMS. You can choose and define different fields for different needs. ...

Craft CMS Vs WordPress: Why Choose Craft?
We are not saying that we do not like WordPress but old man has to move the order to pave way for new and what better...

Pitching Lessons from Shark Tank that Will Save...
Investors have the money, you have the idea, and the right pitch is the only thing that stands between you and them. ...

Is Android Picture-In-Picture Next Step to Inno...
When you look at it for the first time, the Android PIP feature looks pretty dope. It is a classic example of taking ...

Data Security Matters: Know Everything about GD...
“Personal data shall be processed in a manner that ensures appropriate security of the personal data, including prote...

Running Outdated Drupal? You Need to PATCH NOW!
Are you using outdated Drupal version for your website? Your website is open to hackers now! Everyone is calling i...

Google Rolls Out Mobile-First Indexing for Web ...
Google recently announced Mobile-First Indexing after a year and half of extensive experimenting and testing. The sea...

Tool Alert: UI Faces: Easier Design Process IS ...
Dear fellow designers, have you ever felt serendipitous? (yeah yeah I will monitor my Word Porn consumption). That...

Older Apps Might Become Useless After Android P
Google recently came up with a developers’ preview for Android P. The developers have now found a new class in the la...

Social Media Marketing and Its Characteristics ...
Social media networks are mode of social interaction. It is a platform of sharing and discussing information among hu...

Agency Originals: A London-based Design Agency ...
When one of our clients introduced us to his friend’s London-based design agency, the one which cannot be named (Vold...

3 steps in choosing the right development team
So you are ready to jump in and take your business or idea and create an online presence! But with no experience in b...

Moving from Idea to MVP: Enroute Hustle
Building the MVP the right way After ages of working on the idea and dreaming the dream (impostor syndrome is cruel,...