This is a premium alert message you can set from Layout! Get Now!

How to implement typo-friendly search components in your React app

0

A search component serves as a user’s access to an application to easily lookup and access data within an app. Users experience the search component as an interface to communicate with an application.

It enables them to find, sort, and filter various parts of an application’s content through an input field where they can specify search keywords or/and a filter option to filter search results.

There are different approaches to adding search functionality to your web application, such as creating the search component from scratch or using search tools to save time and improve accuracy, and productivity.

In this blog post, you’ll learn step-by-step how to implement a typo-friendly search component in your React app using a simple API.

This article will also compare two search engines (Algolia and Typesense) and look at their advantages over each other to give you a base knowledge on which of them is a better option for search functionality depending on your application needs.

Prerequisites

This article assumes you are familiar with the following:

  • React
  • Application Programming Interface (API)
  • Basic CSS

Table of Contents

What are the things to consider when building a typo-friendly component in React?

Having a typo-friendly search component will provide your users with a better user experience while navigating through your application. When creating a search component, it is essential to note what features you should consider to deliver an efficient search component and an overall satisfying user experience.

Autocomplete feature

This feature automatically provides predictions to complete a word as soon as the user starts to type the word. It saves time as it helps users to quickly complete their desired search query.

Autocorrect feature

This feature provides suggestions to correct typos, incorrect spellings, and capitalization. This relieves a user from needing to ensure if terms are correct to the letter as they search through your application.

Suggest related results feature

This feature provides users with a list of suggested words related to the term they are searching.

Demo application: Typosearch

This demo tutorial will walk through how to build a simple search application using ReactJS, and also how to add typo-friendly features such as correction suggestions and next-word prediction.

The application consists of 3 major components: the SearchBar.js component, the Suggestion.js component, and the overall App.js component that wraps all other components.

When you type in a keyword, it does two things:

  • It tries to predict the likely next word, for example, the word “separate” is most likely succeeded by “from”
  • It suggests some words when you happen to mistype a word. For example, when you type “poople”, it suggests “people” as one of the suggested options to fix the typo.

These features will be implemented using the free Datamuse API, which has 100,000 daily API call limits.

Installation

To get started, clone the project from GitHub.

Install dependencies by running the following command into your terminal:

npm install

Your folder structure should look like this:

Typo search folder structure
Screenshot 2022-06-21 at 11.42.56 PM.png

Run the following command to spin up a local server for previewing the application:

npm run start

The components

There are three components that make up this project and they are:

  • SearchBar Component: This is a simple search field where you type in your search keyword
import React from 'react';
import './SearchBar.css';
import SearchIcon from './SearchIcon';
function SearchBar({ handleSearch, nextWord, searchValue, selectSug }) {
const handleKeyDown = (e) => {
if (e.key === 'Tab') selectSug(false, nextWord);
}
return (
<>
{ searchValue &&Hit the Tab key to accept suggestion

}

{ searchValue && nextWord && {nextWord} } alert(searchValue)}>

</> ) } export default SearchBar;

  • Suggestion Component: this component basically contains three-word suggestions that are meant for correcting your typo entered into the SearchBar component
import React from 'react';
import './Suggestion.css';
function Suggestion({ correctionSugs, searchValue, selectSug }) {
  return (
    <>
    {
      searchValue && correctionSugs.length > 1 &&
      <div className="suggestion">
          <h4 className="suggestion__header">Did you mean?</h4>
          {
            correctionSugs.map(item => {
              return <p className="suggestion__sug" key={item} onClick={() => selectSug(item)}>{item}</p>
            })
          }
      </div>
    }
    </>
  )
}
export default Suggestion;
  • App: This is the home component that encapsulates other components. It performs computations and passes props to components where necessary
Typo friendly search demo
Search component demo

How it works

When you type into the input field, the application makes two API calls. The first call is for predicting the most common next word to your search keyword. When this data is returned from the API, it is stored in a state variable nextWordSug and passed as a prop to the SearchBar.js component where it is rendered. You can hit the Tab button to automatically append the next word suggestion to your search keyword.

try {
  const res = await fetch(`https://api.datamuse.com/words?lc=${word}`);
  const data = await res.json();
  if (data.length > 1) setNextWordSug(data[0].word);
} catch (err) {
  alert('Error occured while getting susggestions!');
}

The other is for suggestion corrections for a mistyped word. When the data is returned from the API, the first three suggestions are extracted, stored in the correctionSugs state variable, and passed as a prop to the Suggestion.js component where it is rendered. You can click on any of the suggestions to accept the suggestion — this replaces your typo with the accepted suggestion.

try {
  const res = await fetch(`https://api.datamuse.com/words?sp=${word}`);
  const data = await res.json();
  let _data = [];
  for (let i = 0; i < 3; i++) {
    if (data.length >= 3) {
      if (data[0].word !== word.toLowerCase()) _data.push(data[i].word);
    }
    setCorrectionSugs(_data);
  }
} catch (err) {
  alert('Error occured while getting susggestions!');
  console.log(err);
}

And that’s all there is to it! You can refer to the source code for in-depth review.

Algolia vs. Typesense

Although you can build a search component in your React application using the method above, you can also leverage search tools to quickly spin up a search component in your React application.

This section of the article compares two efficient search tools — Algolia and Typesense, that you can easily integrate into your React application to improve the search experience of your end users.

Unlike creating a custom search component yourself, these search tools are easier to use, intuitive, and offer several out-of-the-box functionalities such as autocomplete and autocorrect, so that you don’t have to manually code these features yourself.

What is Algolia?

Algolia is a search engine offering that provides you with a set of building blocks for creating a fast, intuitive, and an overall amazing search experience for your users. It offers you auto-correct and complete search functionalities that help your users find answers faster.

It offers a developer-friendly API client, intuitive UX tools and several integrations to help you quickly create a search component in your application. It provides a dashboard for developers to manage their search analytics and allows you also integrate your own analytics tool to see how search.

Global language support

Algolia is language-agnostic, and it has support for symbol-based languages including Chinese, Japanese, Arabic, etc, without requiring any additional work. This means that it supports both left-to-right (LTR) and right-to-left (RTL) scripts.

Typo-tolerance

Typo-tolerance is a feature that tolerates users’ misspellings and provides them with the item they search for. Algolia offers this by matching words that are closest in spelling to the searched word.

What is Typesense?

Typesense is a typo-tolerant search engine that is built using cutting-edge search algorithms, optimized with instant search-as-you-type experiences.

It enhances the search experience with autocomplete, filters, query suggestions, and features. Unlike Algolia, Typesense is open-source, meaning you can host it yourself, but they do offer a cloud-based solution — Typesense Cloud.

No Runtime Dependencies

Typesense is a single binary that requires no runtime dependencies. This means that you can run Typsense locally or in production with a single command.

Simple to setup

Typesense is simple to set up, manage, integrate with, operate, and scale.

Key differences and similarities

  • Algolia offers personalization & server-based search analytics. Typesense on the other hand lets you create your search on the client-side and send search metrics to your preferred web analytics tool
  • Typesense is fully open source, meaning you can either host it yourself (for free) or use its managed SaaS offering — Typesense Cloud. Algolia is a proprietary closed source
  • Both Typesense and Algolia offer you a dashboard which you can use to access your data and index configuration, and also monitor your search analytics
  • Typesense offers instant search-as-you-type experiences for data sets that can fit in RAM, up to 24 TB, while Algolia offers instant search-as-you-type experiences for datasets up to 128 GB in size
  • They both offer features like autocomplete, autocorrect, typo-tolerance, faceting, and more

Conclusion

Search is an important feature that is useful in almost every modern application, especially in eCommerce applications, documentation, databases, and chat applications.

Creating a typo-friendly component in React can be quite a difficult task, especially if you have to build the functionalities yourself. However, leveraging search engine services like Algolia and Typesense can relieve you of the hassle.

Choosing a better search engine for your React app depends on your use case. Algolia is a great choice if cost is not a problem, Typesense on the other hand offers an open-source version that can be self-hosted for free.

Both Algolia and Typesense are categorized as search as a service tools, with several out-of-the-box functionalities to improve the overall user experience.

The post How to implement typo-friendly search components in your React app appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/lOFXiwe
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top