How to Add Search Autocomplete Functionality to Your React Application

Most applications nowadays implement some type of search functionality, allowing users to type some text, get a list of matching values, and select one of these values to retrieve data to populate the page with or to fill out a form.

These search boxes, which provide the user with a list of matching values to select from, are known as AutoComplete controls. As the name implies, the AutoComplete control automatically completes the text string the user is entering, allowing them to select a matching value without typing the entire string out.

We use AutoComplete controls every day. Google’s search bar, as well as Google Maps' location search, are forms of autocomplete, as you can see via the screenshots below:

autocomplete

AutoComplete Map

As you can see, when filling out these AutoComplete controls, they display the text that has been entered as well as other potential choices based on the entered text (for Google Search, the entered text is standard while the auto-filled text is bold, and this styling scheme is reversed for Google Maps.)

Try all of Wijmo's specialized controls with the Enterprise trial! Download today!

We can build a React Autocomplete control from scratch with HTML and JavaScript, but this would take a lot of development work on our part. So instead, we’re going to implement our search functionality by implementing Wijmo’s React AutoComplete control. In this article, we’ll be covering the following:

If you’d like to download this application, you can do so here. You can install Wijmo via NPM or download the library here. NPM is typically the most common way developers install our controls. Still, our library download includes other benefits, such as hundreds of samples available in JavaScript, Angular, React, and Vue and reference apps.

Implementing Wijmo’s React AutoComplete Control

We first need to install Wijmo in our application; that way, we can instantiate the React AutoComplete control. For installation steps, check out our documentation.

Once Wijmo is installed, we’ll need to reference the appropriate files. We’ll only need Wijmo’s CSS, core, and input files for this application. These will be included inside our App.js and index.css files:

index.css

@import '@grapecity/wijmo.styles/themes/wijmo.theme.material.css';

App.js

import * as wjCore from '@grapecity/wijmo';
import * as wjcInput from '@grapecity/wijmo.react.input';

Now that we’ve imported the required files, we can add the code for Wijmo’s React AutoComplete control to the HTML. We’re also going to set a few properties on the control, allowing us to display our data correctly.

<div className='App'>
  <wjcInput.AutoComplete itemsSource={cv} displayMemberPath="state" headerPath="state" isContentHtml={true}></wjcInput.AutoComplete>
</div>

I’ve outlined the purpose of each of these properties below:

  • itemsSource: The data that is going to be displayed
  • displayMemberPath: The property of the data object that we want to bind to
  • headerPath: The property that we want to display in the text area
  • isContentHtml: Tells the control that the custom content will be HTML

Now, headerPath and displayMemberPath may look like similar properties, but this is what allows us to display the selected item in the textbox correctly. Usually, if we modify the displayed content through itemFormatter, that would also be reflected in the textbox. So, for example, if we want to display additional text in the elements of the dropdown, if we do not set the headerPath, this modified text would also display inside of the textbox of the control.

Now that the control has been set up, we need the data to display. For this application, we will display states/provinces of the US, Canada, and Mexico in the AutoComplete control. Our data is going to have the following form:

{
  "state": "Connecticut",
  "country": "United States"
},

To do this, we will set up a CollectionView and make a fetch call. Inside of the fetch call, we’ll assign the data that we retrieve to the CollectionView:

const [cv, setCollectionView] = useState(new wjCore.CollectionView([], {}));
useEffect(() => {
  fetch('https://mocki.io/v1/c8e84317-feaa-40ea-89cf-2af1fb611d49').then(response => response.json()).then(data => cv.sourceCollection = data);
});

The CollectionView is a Wijmo data object designed to manage an array of data. We could also directly assign the array to the control and allow it to create its CollectionView, but this will enable us to modify the CollectionView more easily if we choose to.

Now when we run the application and type in the textbox, we should see the following:

AutoComplete

This is good, but we can do more with this. The following section will cover how to customize the displayed content inside the AutoComplete control.

Customizing Displayed Content

Now we’ve got our React AutoComplete control implemented. But, I like the look of Good Maps' AutoComplete, which shows some additional details on the displayed values. So, we will also display the country in which the state/province is located.

To do this, we will create a custom method and tie it to one of the AutoComplete control’s events: the itemFormatter event.

App.js

function customItemFormatter(index, content) {
  let country = 'N/A';
  for(var i = 0; i < cv.sourceCollection.length; i++) {
    if(content === cv.sourceCollection[i].state) {
      country = cv.sourceCollection[i].country;
    }
  }
  content = '<span class="primary">' + content + ' </span><span class="secondary">' + country + '</span>';
  return content;
}
....
<wjcInput.AutoComplete itemsSource={cv} displayMemberPath="state" headerPath="state" isContentHtml={true} itemFormatter={customItemFormatter.bind(this)}></wjcInput.AutoComplete>

The itemFormatter event gets fired whenever an element for the dropdown list gets created. So this will allow us to customize the content for each item in the dropdown list.

We want to display the country of the state/province, so all we need to do is parse through our array of data, find the item that has a matching state to the content being displayed, and append the country to the content string.

We’re also defining some HTML inside this string; if you remember, earlier, we told the AutoComplete control that the content it displays would be HTML. We’re going to use the classes that are assigned to the <spans> to style the control some more in the next section.

Now when we run the application, we should see the following:

AutoComplete

As you can see, when we search, it also displays the country. When we make a selection, you can see that it only shows the name of the state/province:

AutoComplete

That is due to the headerPath property that we set earlier.

In the next section, we’ll go over how you can style the control to fit your application's design.

Styling the AutoComplete Control

Now that our control displays the data in the format we want, it's time to add some styling to the control. We’ll first style the text using the <span> tags that we added in the last section.

App.css

.primary {
  font-weight: bold;
}

.secondary {
  font-size: small;
  color: gray;
}

This will help us highlight the primary text they’re searching (the state/province) while taking some focus off of the country text.

We have two options for applying style to the control itself. The first is to use one of Wijmo’s built-in style options. You can find a full list of options here. The second option is to apply our own styles. For this application, we’re going to do our own styling.

Before we get into styling the control, there’s one thing that needs to be pointed out. When making changes to Wijmo CSS classes, for these changes to be applied to the controls, you must include the CSS in your highest-level CSS file; in the case of this application, that would be the index.css file.

index.css

.wj-control.wj-content.wj-dropdown, .wj-control.wj-content.wj-inputnumber, .wj-control.wj-content.wj-inputmask {
  color: hsl(0, 0%, 80%);
  background: hsl(0, 0%, 33%);
}

.wj-control .wj-input-group .wj-input-group-btn:last-child:not(:first-child)>.wj-btn, .wj-viewer .wj-control .wj-input-group .wj-input-group-btn:last-child:not(:first-child)>.wj-applybutton {
  color: hsl(0, 0%, 80%);
}

.wj-control .wj-input-group .wj-form-control {
  color: hsl(0, 0%, 80%);
  background: hsl(0, 0%, 33%);
  width: 100% !important;
}

.wj-listbox .wj-listbox-item {
  color: hsl(0, 0%, 80%);
  background: hsl(0, 0%, 33%);
}

.wj-listbox .wj-listbox-item:hover {
  background: hsl(0, 0%, 27%) !important;
  cursor: pointer;
}

.wj-listbox-item.wj-state-selected {
  background: hsl(0, 0%, 27%);
}

.wj-control .wj-btn:hover {
  background: hsl(0, 0%, 45%);
}

Now, to explain the CSS that we’ve added. The first two elements we’re modifying will change the text’s color, background, and glyph displayed when a user loads our control.

Now, when we run our application, we should see some changes to the React AutoComplete control:

AutoComplete

As you can see, it has more of a night-mode feel to it now. Next, we’ll need to ensure that our dropdown matches the textbox portion of the control. The rest of the CSS that we’ve written does just that! The CSS will change the background, text color, and hover effects for the dropdown portion of our AutoComplete control. When we run it, we should see the following:

AutoComplete

As you can see, the background color now matches throughout the entire control; we also have a nice highlight color to differentiate what we have selected/are hovering from the rest of the elements in the list.

Conclusion

As you can see, you can easily include search functionality using Wijmo’s React AutoComplete control. If you'd like more information, we've got demos, documentation, and API references for developers. If you'd like to download the finished application, you can find it here.

If you're interested in seeing what more Wijmo has to offer, you can download the library here and via NPM. Downloading from our website includes hundreds of samples and reference apps you can use when building your application.

Try all of Wijmo's specialized controls with the Enterprise trial! Download today!

Happy coding!

Tags:

comments powered by Disqus