How to Create a type and search Component in Next.js React?

Here is an example of how you can create a type-and-search component in Next.js using the useState hook and the fetch function:

import { useState } from 'react';
 
function TypeAndSearch({ data }) {
  const [searchTerm, setSearchTerm] = useState('');
  const [results, setResults] = useState([]);
 
  async function handleSearch(e) {
    e.preventDefault();
    const response = await fetch(`/api/search?q=${searchTerm}`);
    const data = await response.json();
    setResults(data);
  }
 
  return (
    <form onSubmit={handleSearch}>
      <input
        type="text"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
      />
      <button type="submit">Search</button>
      <ul>
        {results.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </form>
  );
}
 
export default TypeAndSearch;

In this example, the TypeAndSearch component has a state variable searchTerm that is used to store the search term entered by the user, and a state variable results that is used to store the search results. The handleSearch function is called when the form is submitted and uses the fetch function to send a request to the server with the search term. The server should return a JSON array of search results, which is then stored in the results state variable. The TypeAndSearch component then displays the search results in an unordered list.

0 Shares:
You May Also Like
AngularJS vs ReactJS vs NodeJS – Which One Is Best?
Read More

AngularJS vs ReactJS vs NodeJS – Which One Is Best?

Nowadays “AngularJS vs ReactJS vs NodeJS” has become a hot topic of discussion because for every business owner, choosing the right JavaScript framework to develop an efficient web application is one of the most crucial decision which would ultimately help them to build a stronger brand image online.
Read More