Input Search in React - Machine coding question

·

2 min read

Searching for a text from a huge list can be done using includes method of javascript and the list can be filtered out using filter method of javascript.

Introduction to includes() in javascript

include() in js string: It would give us either true or false based on if the element is found in the text or not.

text.includes("search-text");

include() in js array: It would give us true if the array contains the element

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango")

For searching a text, we would need a combination of both and then we can filter it based on whether the text includes search-text or not.

setFilteredBrands(
   brands1.filter((brand) => brand.brandName.includes(e.target.value))
);

This is the magic function that does the whole job. It checks if the brandName which is a text, includes the search text coming from e.target.value or not.

Below, is the code for the input-search

function App() {
  const brands1 = [
    { id: "0a", brandName: "puma" },
    { id: "0b", brandName: "adiddas" },
    { id: "0c", brandName: "wildcraft" },
    { id: "0d", brandName: "levis" },
    { id: "0e", brandName: "celio" },
  ];
  const [filteredBrands, setFilteredBrands] = useState([]);
  const handleSearchBrand = (e) => {
    setFilteredBrands(
      brands1.filter((brand) => brand.brandName.includes(e.target.value))
    );
  };
  return (
    <div className="App">
      <h4>BRAND</h4>
      <div className="brand-input">
        <AiOutlineSearch />
        <input type="text" onChange={handleSearchBrand} />
      </div>
      {filteredBrands.length > 0 &&
        filteredBrands.map((brand) => 
          <p key={brand.id}>{brand.brandName}</p>
        )}
    </div>
  );
}

Here's the link to the code:- https://codesandbox.io/p/github/kumsomi/brand-filter/master?file=/src/App.jsx:3,1&workspaceId=d23e40a9-77f2-41d3-b773-bc02f0d7c859

Thanks for reading. If you want to continue the conversation. We can connect on Linkedin and twitter or you can comment down below for further queries.