Build more accessible forms with React Icons
Tags: react, javascript, ui
Published: 2020-01-27 13:56:23

---
title: Build more accessible forms with React Icons
published: true
date: 2020-01-24 18:31:08 UTC
tags: react,javascript,ui
canonical_url: https://blog.logrocket.com/build-more-accessible-forms-with-react-icons/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/isbm37ixsklkzbfi4eko.png
---
**Written by [Peter Ekene Eze](https://blog.logrocket.com/author/peterekeneeze/)**✏️

Taking extra measures to build more accessible React apps can be a time-consuming process. However, it’s something we need to do in order to create a more inclusive web for everyone.

The goal of this post is to help you understand how to build more accessible React forms by using the popular [react-icons library](https://react-icons.netlify.com) and the very accessible React components made available by the [ReachUI library](https://reacttraining.com/reach-ui/).

## Why React Icons?

[React Icons](https://react-icons.netlify.com) provides thousands of free, open-source icons. It includes ten popular open-source icon libraries, including Font Awesome and Material Design. It utilizes ES6 imports that allow you to include only the icons that your project is using. We use react-icons for a number of reasons, mostly to target user inputs and add visual descriptions to form fields. Here are some benefits:

- The quick installation process (it can be installed via npm)
- All react-icons are optimized for accessibility by default
- Finding variations of numerous icons are easier
- Memory friendly, it doesn’t leave a big footprint in your bundle
- It ensures minimal file size with SVG (scalable vector graphics) options
- It’s open-source so it can be used on both commercial and non-commercial projects

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## Building an accessible React form

### Prerequisites

- Prior knowledge of React will be helpful but not mandatory
- You should have [Xcode](https://developer.apple.com/xcode/) or [Android Studio](https://developer.android.com/studio) installed to run the simulator/emulator
- You should have [Node 10+](https://nodejs.org/en/download/current/) installed

### What we’ll build

For demonstration purposes and to give you a more practical experience, we’ll build a contact form to collect the details of a new friend. We’ll make this form accessible using Reach UI’s components and React Icons. Here’s a visual output of the end product.

![finished ui with icons](https://i1.wp.com/blog.logrocket.com/wp-content/uploads/2020/01/iconsform.gif?resize=730%2C500&ssl=1)

## Getting started

The most common way to start a React project is by using the [create-react-app](https://reactjs.org/docs/create-a-new-react-app.html) CLI tool. If you haven’t done this before, go ahead and run the following commands to install the necessary packages and start the local development server:

```jsx
npx create-react-app accessible-form
cd accessible-form
npm start
```

If you check your browser on `localhost:3000`, you should see your project live.

![](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/01/newprojectreact.gif?resize=730%2C589&ssl=1)

Icons have become an integral part of creating a great user interface. They help present your content in a clear and concise manner that would make navigating your website or application easier for your users.

## Building the contact form

To build the form fields we make use of the components made available to us from [ReachUI](https://reacttraining.com/reach-ui/). To find out more of ReachUI’s components, visit [ReachUI components](https://reacttraining.com/reach-ui/).

## Dependencies

To help us build this project, we’ll reuse some existing libraries:

1. [ReachUI](https://reacttraining.com/reach-ui/) — For building and styling the form in the most accessibility-friendly way
2. [React Icons](https://www.npmjs.com/package/react-icons) — To provide the necessary icons for the form fields
3. [Bootstrap](https://www.npmjs.com/package/bootstrap) — To build a more responsive form across all kinds of screen sizes
4. [React DatePicker](https://www.npmjs.com/package/react-datepicker) — A simple component that helps implement date picking in React apps

To install these libraries, open a terminal and run the following commands in the project’s root folder:

```jsx
npm install --save react-icons react-datepicker bootstrap
```

In the root directory of the sample project we created, create a new  
`src/components/Contact.js` file. In this file, we’ll set up our contact form and use `react-icons` to improve its accessibility and overall experience. Open it up and update it with the code below:

```jsx
import React, { Component } from "react";
import { Combobox, ComboboxInput } from "@reach/combobox";
import { Menu, MenuList, MenuButton, MenuItem } from "@reach/menu-button";
import {
  MdPhone,
  MdPermIdentity,
  MdLocationOn,
  MdEmail,
  MdExpandMore,
  MdEvent
} from "react-icons/md";
import DatePicker from "react-datepicker";
class Contact extends Component {
  render(){
    return(
      <>  
      //Form here
      </>
    );
  }
}
```

Here, we’ve imported a few of the external components that we installed earlier to help us implement the functionalities needed in this application. Let’s take a closer look at their respective features:

- [`<Combobox>`](https://reacttraining.com/reach-ui/combobox): This is an accessible input box component made available by the ReachUI library. Like every other component from the ReachUI library, it is accessible by default and abides by all ARIA element specifications
- [`<Menu/>`](https://reacttraining.com/reach-ui/menu-button): The ReachUI Menu component is used to provide dropdown selection functionalities in web apps. In our form, we’ll have a dropdown menu that allows users to select the locations they reside in. Using the `<Menu/>` component gives us accessibility out of the box and also makes the menu items keyboard accessible. Finally, the menu options are well suited for assistive technologies
- [`<React Icons/>`](https://www.npmjs.com/package/react-icons): The icons we imported into this project are all from [material design icons](https://react-icons.netlify.com/#/icons/md) made available to us by the react-icons library. It makes our form fields more visually descriptive
- [`React DatePicker`](https://www.npmjs.com/package/react-datepicker): This a reusable Datepicker component made specifically for building React applications. We’ll use this component to render the date picker for the birthday selection field. It is keyboard accessible and renders the date efficiently

Having imported all the necessary external libraries, we can go ahead and define the `return()` function in our `Contact.js` file. In it, we’ll use the components we’ve imported to build out the desired form fields.

## The name input field

This is the form field that collects the name of the user. To set this up, we’ll update the previous snippet with the code below:

```jsx
// imports
class Contact extends Component {
  render(){
    return(
      <>  
        <form onSubmit={this.handleSubmit}>
          <Combobox>
            <div>
              <label for="userName">
                <MdPermIdentity />
              </label>
            </div>
            <div>
              <ComboboxInput
                className="form-control"
                id="userName"
                aria-label="user name"
                name="userName"
                value={this.state.userName}
                placeholder="Name"
                onChange={this.handleChange}
              />
            </div>
          </Combobox>        
        </form>
      </>
    );
  }
}
export default Contact     
```

![combo box](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2020/01/combobox.png?resize=730%2C346&ssl=1)

Here, we used the `<Combobox/>` component to define the field that collects the user’s name. While rendering the `MDPermIdentity` icon, we wrapped it inside a HTML `label` tag to add more visual accessibility to the form input using the `for` attribute it provides. Finally, to render the text input component for the field, we used the `ComboboxInput` component which takes in the `aria-label` attribute to provide audio accessibility to users who make use of screen-readers.

We’ve also applied the same functionality across all other fields that enable users to input text such as the phone number field, the address field, and the email field.

## The area input field

This is the field where we’ll allow users to select a residential location based on a predefined list of locations. We’ll use the `<Menu/>` component from ReachUI to accessibly power this functionality. Here’s how we implement that in the `Contact.js` file:

```jsx
// imports
class Contact extends Component {
  render(){
    return(
      <>  
        <form onSubmit={this.handleSubmit}>
          <div>
            <Menu>
                <MenuButton aria-label="menu button for area">
                  {(this.state.userArea == '') ? ('Area') : (this.state.userArea)}
                  <span aria-hidden><MdExpandMore /></span>
                </MenuButton>
                <MenuList>
                  <MenuItem onSelect={() => this.handleSelect('Ajah', 'userArea' )}>
                    Ajah
                  </MenuItem>
                  <MenuItem onSelect={() => this.handleSelect('Apapa', 'userArea' )}>
                    Apapa
                  </MenuItem>
                  <MenuItem onSelect={() => this.handleSelect('Festac', 'userArea' )}>
                    Festac
                  </MenuItem>
                  <MenuItem
                    onSelect={() => this.handleSelect('Gbagada', 'userArea' )}>
                    Gbagada
                  </MenuItem>
                  <MenuItem onSelect={() => this.handleSelect('Lekki', 'userArea' )}>
                    Lekki
                  </MenuItem>
                  <MenuItem
                    onSelect={()=> this.handleSelect('Victoria Island', 'userArea' )}>
                    Victoria Island
                  </MenuItem>
                </MenuList>
              </Menu>
            </div>
          </div>
        </form>
      </>
    );
  }
}
export default Contact
```

The Menu component has some extended accessibility features, however, it is still practically a wrapper around the usual HTML elements in the following ways:

- `<Menu />` component — HTML `<select />` HTML element
- `<Menubutton />` — HTML `<button />` element
- `<MenuItem/>` — HTML `<option/>` attribute for `<select/>` elements
- `<MenuList />` — wrapper for the `<MenuItem />`

Once again, we’ve used the `aria-label` to provide audio accessibility for screen-readers.

## Conclusion

![finished app](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2020/01/finishedapp.gif?resize=730%2C500&ssl=1)

Congratulations! You just finished building an accessible contact form in React using React Icons and ReachUI. The goal is to help you get an immediate hands-on approach to building accessible React forms. We didn’t cover the styling of the form in detail so as not to divert attention from the more important aspect of this post. However, you can find the source code with all the styles in the [project repository.](https://github.com/kenny-io/accessible-react-form)

* * * 
## Full visibility into production React apps 

Debugging React applications can be difficult, especially when users experience issues that are difficult to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, [try LogRocket.](https://www2.logrocket.com/react-performance-monitoring)

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/eq752g8qhbffxt3hp9t4.png)

[LogRocket](https://www2.logrocket.com/react-performance-monitoring) is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — [start monitoring for free.](https://www2.logrocket.com/react-performance-monitoring)
* * *

The post [Build more accessible forms with React Icons](https://blog.logrocket.com/build-more-accessible-forms-with-react-icons/) appeared first on [LogRocket Blog](https://blog.logrocket.com).