The complete guide Handling a Forms in React 🚀🚀🚀

The complete guide Handling a Forms in React 🚀🚀🚀

In this article, you will learn how to use a form in React and how to handle text inputs, radio buttons, checkboxes, selects and other input types.

In this article, you will learn how to use a form in React and how to handle text inputs, radio buttons, checkboxes, selects and other input types.

Web applications often need to send data from browser to the backend server. Certainly, the most used way of doing so is through a HTML form, by using text inputs, radio buttons, checkboxes, selects and so on. This remains true in React. Are you looking how to handle forms in React? If so, this article is a great fit for you. Have a good read.

Controlled vs Uncontrolled components

In React, when a component renders a form with elements such as text inputs, selects or checkboxes, there are two ways of keeping and updating their state:

  1. The state is kept and updated by the input itself. This is the way forms work in pure HTML.
  2. The state is handled by the component that renders the form. It uses the component’s state for such purpose and leverages event handlers to detect changes and keep the state up-to-date.** This is the recommended way of handling forms in React.**

In the first approach, React has no control over the input’s state. Therefore, these form inputs are called uncontrolled components.

In the second approach, however, React controls the input’s state. For this reason, such inputs are called controlled components.

As controlled components are the way to go in React, I won’t cover uncontrolled components in this article.

Text inputs

You need to use the value attribute and the onChange event in order to handle text inputs. Check out this example:

export default class App extends Component {
  state = { name: '' };
  
  handleNameChange = (e) => {/*...*/}
  
  render() {
    return (
      <div>
        <form>
          <label>Name:</label>
          <input value={this.state.name} onChange={this.handleNameChange} type="text" />
        </form>
      </div>
    );
  }
}

In the above component, every time a change occurs in our input, the handleNameChange event handler is called. Let’s take a look at it:

handleNameChange = (e) => {
  const name = e.target.value;
  this.setState({ name });
};

Well, there’s nothing special here. This handler receives an event object that holds, among other things, the up-to-date value of the input. After getting it, this same value is assigned to its matching entry in the component’s state by using the setState method.

After the change is performed, the value attribute of the input is automatically updated, since the this.state.name state entry is bound to it. To make it more visible, you can update your code to print the input value:

render() {
  return (
    <div>
      <form>
        <label>Name:</label>
        <input value={this.state.name} onChange={this.handleNameChange} type="text" />
      </form>
      <strong>The typed name is: </strong><span>{this.state.name}</span>
    </div>
  );
}

Let’s use the React Developer Tools extension to see how it behaves:

As you can see, every time a change happens, the component’s state is updated and, as a consequence, the value attribute of the input too.

Textareas

In pure HTML, a textarea has no value attribute. Its value is defined by its content. In React, however, textareas and common text inputs are handled in a very similar way:

export default class App extends Component {
  state = { bio: '' };

  handleBioChange = (e) => {
    const bio = e.target.value;
    this.setState({ bio });
  };

  render() {
    return (
      <form>
        <label>Bio:</label>
        <textarea value={this.state.bio} onChange={this.handleBioChange} />
      </form>
    );
  }
}

As you may have noticed, the above code is almost identical to the text input example. In both, we use the onChange event and the value attribute to keep the component’s and input’s states synchronized.

Selects

Similarly to textareas, select tags also have no value attribute in HTML. However, their children – option tags – do have it. To set the value of a select tag, you’d need to add a selected attribute to one of its options. React favors a simpler approach, by bringing the simplicity of the value attribute to select tags:

render() {
  return (
    <form>
      <label>Desired color:</label>
      <select value={this.state.color} onChange={this.handleColorChange}>
        <option></option>
        <option value="blue">Blue</option>
        <option value="red">Red</option>
        <option value="green">Green</option>
        <option value="yellow">Yellow</option>
      </select>
    </form>
  );
}

The handleColorChange event handler has nothing new:

handleColorChange = (e) => {
  const color = e.target.value;
  this.setState({ color });
};

If you want your dropdown to have multiple values selected, set the multiple attribute to true and assign an array as its value, like this:

render() {
  return (
    <form>
      <label>Desired color:</label>
      <select multiple={true} value={['blue', 'red']}>
        <option></option>
        <option value="blue">Blue</option>
        <option value="red">Red</option>
        <option value="green">Green</option>
        <option value="yellow">Yellow</option>
      </select>
    </form>
  );
}

Checkboxes

**Checkboxes **use the checked attribute instead of the value one. Both work in a very similar manner, but the value of the checked attribute must be a boolean. Check out this example:

state = { acceptedAgreement: false };

handleAcceptAgreementChange = (e) => {
  const acceptedAgreement = e.target.checked;
  this.setState({ acceptedAgreement });
};

render() {
  return (
    <form>
      <label>
        I accept the agreement
        <input
          checked={this.state.acceptedAgreement}
          onChange={this.handleAcceptAgreementChange}
          type="checkbox" />
      </label>
    </form>
  );
}

Let’s see how it works under the hood:

Radio buttons

Radio buttons are treated differently in React. The most common way of handling a group of radio buttons is by using both value and checked attributes together:

<form>
  <label>
    Beginner
    <input
      value="BEGINNER"
      checked={this.state.skillLevel === 'BEGINNER'}
      onChange={this.handleSkillLevelChange}
      type="radio" />
  </label>
  <label>
    Intermediate
    <input
      value="INTERMEDIATE"
      checked={this.state.skillLevel === 'INTERMEDIATE'}
      onChange={this.handleSkillLevelChange}
      type="radio" />
  </label>
  <label>
    Advanced
    <input
      value="ADVANCED"
      checked={this.state.skillLevel === 'ADVANCED'}
      onChange={this.handleSkillLevelChange}
      type="radio" />
  </label>
</form>

In traditional HTML, in order to create a group of radio buttons, you need to use the name attribute. As you can see in the above code, we don’t need to do this in React. This is because the this.state.skillLevel === […] condition in each checked attribute implements the needed grouping logic, once it won’t be possible to check two radio buttons at the same time.

Here’s the handleSkillLevelChange event handler (it’s identical to the above examples):

handleSkillLevelChange = (e) => {
  const skillLevel = e.target.value;
  this.setState({ skillLevel });
};

As you may have noticed, there’s a lot of repeated code in the render method of this component. You could make it shorter by creating an array of options and using the map method to render each option as a separate radio button.

render() {
  const levels = ['Beginner', 'Intermediate', 'Advanced'];
  return (
    <form>
      {levels.map((level, index) =>
        <label key={index}>
          {level}
          <input
            value={level.toUpperCase()}
            checked={this.state.skillLevel === level.toUpperCase()}
            onChange={this.handleSkillLevelChange}
            type="radio" />
        </label>
      )}
    </form>
  );
}

Forms with multiple inputs

To put it all together, let’s handle a form with multiple inputs:

render() {
  const colors = ['Blue', 'Red', 'Green', 'Yellow'];
  const sizes = ['Small', 'Medium', 'Large', 'XL', 'XXL', '3XL'];
  
  return (
    <form>
      <ul>
        <li>
          <label>Name:</label>
          <input name="name" type="text" value={this.state.name} onChange={this.handleChanges} />
        </li>
        <li>
          <label>Observation:</label>
          <textarea name="observation" value={this.state.observation} onChange={this.handleChanges} />
        </li>
        <li>
          <label>Desired color:</label>
          <select name="color" value={this.state.color} onChange={this.handleChanges}>
            {colors.map((color, i) => <option key={i} value={color.toLowerCase()}>{color}</option>)}
          </select>
        </li>
        <li>
          <label>T-shirt Size:</label>
          {sizes.map((size, i) =>
            <label key={i}>
              {size}
              <input
                name="size"
                value={size.toUpperCase()}
                checked={this.state.size === size.toUpperCase()}
                onChange={this.handleChanges}
                type="radio" />
            </label>
          )}
        </li>
        <li>
          <label>
            I accept the agreement
            <input name="acceptedAgreement" type="checkbox" value={this.state.acceptAgreement} onChange={this.handleChanges} />
          </label>
        </li>
      </ul>
    </form>
  );
}

In the above form, we’re using all input types we’ve seen so far. Note that I also added a name attribute to each input, so it will be a lot easier to distinguish between them.

This is how our state object looks like:

state = {
  name: '',
  observation: '',
  color: '',
  size: '',
  acceptedAgreement: false
};

And finally, here’s the final version of the handleChanges event handler:

handleChanges = (e) => {
  const input = e.target;
  const name = input.name;
  const value = input.type === 'checkbox' ? input.checked : input.value;
  this.setState({ [name]: value });
};

As you can see, I use the name property to know which input has triggered the event. I also test if the input is a checkbox. If it is, I get its value through the checked property, if not, I use the value property.

Check out how it works:

Handling the form submission

Finally, to handle the form submission, you just need to define a handler for the onSubmit event:

handleFormSubmit = (event) => {
  console.log(this.state.name)
  event.preventDefault();
};

render() {
  return (
    <form onSubmit={this.handleFormSubmit}>
      <label>Name:</label>
      <input type="text" value={this.state.name} onChange={this.handleNameChange} />
      <button type="submit">Send</button>
    </form>
  );
}

In this event handler, you could submit the values of your form to an endpoint by using, for example, the fetch API. You also need to call the event.preventDefault method to prevent a traditional form submission, which reloads the entire page.

What about file inputs?

As the value of a file input is read-only, this type of input can’t be controlled by React, therefore, file inputs will always be uncontrolled. If you want to implement file upload in React, take a look at this article.

Conclusion
  • An input’s state can be **handled by React **(controlled component) or by itself (uncontrolled component).
  • Controlled components are the recommended way of handling forms in React.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company

React Web Development: A Guide to Develop Progressive Web Applications

React Web Development: A Guide to Develop Progressive Web Applications

Outperform your competition with progressive web development and React.

Progressive web applications (PWAs) quickly gained popularity because they are web performance applications based on fast performance, streamlined to provide a mobile app-like experience. PWAs are built using HTML, CSS, and JavaScript to create a level of availability and performance equivalent to that of native mobile applications. They respond quickly, consume less data, store more space, and support push notifications and offline use in the browser.

Building a progressive web application has now become the web development trend that every business wants to follow. Significant players like Twitter and Flipboard have recently rolled out their progressive web apps to provide a mobile experience for users, without requiring them to install the app. In this article, you will learn how to build a progressive web application using React. Let's get started.

Step One — Set up the React Application

First, create a React application with create-react-app. To do so, you need to run the following commands:

  • npm install -g create-react-app
  • create-react-app pwa-app

Now, install React Router:

You need to replace the content of src / App.js using the code below to get a basic template with navigation.

import React, { Component } from 'react';
import { Router, browserHistory, Route, Link } from 'react-router';
import './App.css';

const NavBar = () => (
<div className="navbar">
<Link to="/">Feed</Link>
<Link to="/profile">Profile</Link>
</div>
);

const Template = ({ title }) => (
<div>
<NavBar />
<p className="page-info">
This is the {title} page.
</p>
</div>
);

const Feed = (props) => (
<Template title="Feed"/>
);

const Profile = (props) => (
<Template title="Profile"/>
);

class App extends Component {
render() {
return (
<Router history={browserHistory}>
<Route path="/" component={Feed}/>
<Route path="/profile" component={Profile}/>
</Router>
);
}
}
export default App;

Now, you'll have to update the default styles by replacing your src/App.css with the styles below to make your application look clean.

.navbar {
background-color: #01C8E5;
text-align: center;
}

.navbar a {
display: inline-block;
padding: 10px;
color: #fff;
text-decoration: none;
}

.page-info {
text-align: center;
font-weight: bold;
}

Then, run npm start to test the application in the browser. It is basically an application with two routes. Now, you will convert it to PWA.

Step Two — Lighthouse Setting and Auditing

Lighthouse is an automated open-source tool for testing applications against PWA checklists. It facilitates audits for accessibility, performance, and more.

Check your application with Lighthouse. Click the Lighthouse icon from the top right corner in Chrome and then click the "Create Report" button. The generated report will look like this:

Creating a report to test your PWA with Lighthouse

Fix all failed audits.

Step 3 — Sign Up for a Service Staff

Service employees are proxy servers that connect the application and the network. With Service Worker, you will have to block network requests and save cached files. It allows your application to work even with an unavailable system.

Create an empty worker.js file in your application's general directory and add the following code to that file.

// Flag for enabling cache in production
var doCache = false;

var CACHE_NAME = 'pwa-app-cache';

// Delete old caches
self.addEventListener('activate', event => {
const currentCachelist = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!currentCachelist.includes(key)) {
return caches.delete(key);
}
}))
)
);
});

// This triggers when user starts the app
self.addEventListener('install', function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
fetch('asset-manifest.json')
.then(response => {
response.json();
})
.then(assets => {
// We will cache initial page and the main.js
// We could also cache assets like CSS and images
const urlsToCache = [
'/',
assets['main.js']
];
cache.addAll(urlsToCache);
})
})
);
}
});

// Here we intercept request and serve up the matching files
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});

Now, check if the browsers support service staff and then register worker.js. To do this, you need to add the following script to the file public/index.html (note that shrink-to-fit=no in the viewport meta tag has been deleted).

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
</script>
</body>
</html>

You must restart your application and reload the browser after which you will see the Successful registration of member workers on the developer console. Now, recreate the Lighthouse report.

Step 4 - Improve the Progressive Nature of the Application

Your application will display an original blank div until the JavaScript loads and React hooks the original route. You must make sure your application works without downloading JS and displaying a bit of CSS and HTML before React takes effect. Your updated Index.html will look like this:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
<style type="text/css">
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
.navbar {
background-color: #01C8E5;
text-align: center;
}
.navbar a {
display: inline-block;
padding: 10px;
color: #fff;
text-decoration: none;
}
.page-info {
text-align: center;
font-weight: bold;
}
</style>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">
<div class="navbar">
<a href="/">Feed</a>
</div>
<p class="page-info">
Loading an awesome app...
</p>
</div>
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('worker.js').then(function(registration) {
console.log('Worker registration successful', registration.scope);
}, function(err) {
console.log('Worker registration failed', err);
}).catch(function(err) {
console.log(err);
});
});
} else {
console.log('Service Worker is not supported by browser.');
}
</script>
</body>
</html>

Now, use Lighthouse to retest your application, and you'll see an improvement in the performance of the application.

Step 5 - Add the Splash Icon

You are required to add a 512x512 icon to display on the screen. To do so, you will have to update the manifest.json file and add the t0 icon to the public directory.

{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"start_url": "/",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

Also, use the following meta tags to allow the browser to determine that your application is a PWA.

<!-- Tell the browser it's a PWA -->
<meta name="mobile-web-app-capable" content="yes">
<!-- Tell iOS it's a PWA -->
<meta name="apple-mobile-web-app-capable" content="yes">
Step 6 — Implement PWA

Now, only HTTPS is missing, and the cache can be fixed after you deploy the application. Update the doCache flag with true in the worker.js file. Create a new project in the firebase dashboard and name it "Pwa Application." Then, run the following command in the project directory:

npm install -g firebase-tools
firebase login
firebase init

Your Firebase.json will look like this:

{
"hosting": {
"public": "build",
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
}
}

After initializing, building and deploying your application.

  • npm run build
  • firebase deploy

You will see results after you test the application using Lighthouse on the deployed URL.

Final product with Lighthouse

Finally, you have created your first progressive web application with React.js!

Originally published by Manoj Kumar Bardhan at  dzone.com

=======================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Understanding TypeScript

☞ Typescript Masterclass & FREE E-Book

☞ React - The Complete Guide (incl Hooks, React Router, Redux)

☞ Modern React with Redux [2019 Update]

☞ The Complete React Developer Course (w/ Hooks and Redux)

☞ React JS Web Development - The Essentials Bootcamp

☞ React JS, Angular & Vue JS - Quickstart & Comparison

☞ The Complete React Js & Redux Course - Build Modern Web Apps

☞ React JS and Redux Bootcamp - Master React Web Development


ReactJS Development Company in Canada| Hire React JS Developers

a successful and trustworthy ReactJS development company in Ontario, Canada with presence in India. Hire our professional React JS developer who will guarantee you the custom ReactJS development and create bug-free, creative, seamless and interactive user interface apps. Get our services at the most competitive prices.