Building a TypeHead component in React

In my recent job search, I have been interviewed at many companies, In one of the interviews, the Interviewer asked me to create a TypeHead Component, where there will be an input box once the user types something in the input, it should give the suggestion key works based on the input.

Building a TypeHead component in React

In modern applications, providing real-time feedback and suggestions to users is crucial for enhancing user experience. One common feature that achieves this is a typeahead or autocomplete component. In this blog, we’ll walk through creating a typeahead component in React Native that suggests matching items as the user types in an input field. Users should see the below content based on the user’s input.

const content = [
  "Rowdy Coders",
  "Javascript",
  "React JS",
  "React Native",
  "HTML",
  "CSS",
  "TypeScript",
];


Setting Up the Input: Based on the input provided in the TextInput field, our search state should update.

const [search, setSearch] = useState("");

const handleChange = (e) => {
  setSearch(e);
};
  
.........................................................
  
<TextInput
  placeholder="Search"
  style={styles.input}
  onChangeText={handleChange}
  value={search}
/>


Fetching Matching Content: Once there is a change in the search, we will call the matching content logic as below with useEffect.

const [data, setData] = useState([]);

  
  useEffect(() => {
    if (search === "") {
      setData([]);
      return;
    }
    const result = [];
    content.forEach((s) => {
      if (
        s.substring(0, search.length).toUpperCase() === 
        search.toUpperCase()
      ) {
        result.push(s);
      }
    });
    setData(result);
  }, [search]);


Based on the matching data state, we will show the data on screen. Below is the whole component.

import React, { useState, useEffect } from "react";
import {
  StyleSheet,
  Text,
  TextInput,
  View,
  TouchableOpacity,
} from "react-native";

const content = [
  "Rowdy Coders",
  "Javascript",
  "React JS",
  "React Native",
  "HTML",
  "CSS",
  "TypeScript",
];

// Create a typeahead component
export default function TypeHeadComponent() {
  const [data, setData] = useState([]);
  const [search, setSearch] = useState("");

  const handleChange = (e) => {
    setSearch(e);
  };

  const handleValue = (d) => {
    setSearch(d);
  };

  useEffect(() => {
    if (search === "") {
      setData([]);
      return;
    }
    const result = [];
    content.forEach((s) => {
      if (
        s.substring(0, search.length).toUpperCase() === search.toUpperCase()
      ) {
        result.push(s);
      }
    });
    setData(result);
  }, [search]);

  return (
    <View style={style.mainContent}>
      <TextInput
        placeholder="Name"
        style={style.input}
        onChangeText={(e) => handleChange(e)}
        value={search}
      />
      {data.map((d) => {
        return (
          <TouchableOpacity
            style={style.typehead}
            key={d}
            onPress={() => handleValue(d)}
          >
            <Text>{d}</Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}

const style = StyleSheet.create({
  mainContent: {
    flex: 1,
    backgroundColor: "white",
    padding: 16,
  },
  input: {
    borderWidth: 1,
    borderColor: "#ccc",
    padding: 8,
    marginBottom: 16,
  },
  typehead: {
    borderWidth: 1,
    borderColor: "#ccc",
    padding: 8,
    backgroundColor: "gray",
  },
});

There can be many other types of similar questions, where the interviewer expects you to get the matching content from an API or the interviewer expects you to call the matching logic with Throttling logic or you might see the similar question in ReactJS as well.