DEV Community

Ayush Rudani
Ayush Rudani

Posted on

Search functionality in Next.js

Here's a simple way to add search functionality in Next.js.

First, you need to have a state for your search input and the list of elements. You can use React's useState for this.

import { useState } from 'react';

export default function Home() {
  const [search, setSearch] = useState('');
  const [list, setList] = useState([]); // This should be your fetched list
  ...
}
Enter fullscreen mode Exit fullscreen mode

Next, create an input field for the search. The onChange event will update your search state every time the user types into the field.

<input
  type="text"
  value={search}
  onChange={(e) => setSearch(e.target.value)}
  placeholder="Search..."
/>
Enter fullscreen mode Exit fullscreen mode

Now, filter your list based on the search input. You can use JavaScript's filter method for this. This will create a new array with all the elements that pass the test implemented by the provided function.

const filteredList = list.filter((item) =>
  item.toLowerCase().includes(search.toLowerCase())
);
Enter fullscreen mode Exit fullscreen mode

Finally, map through your filteredList to display the items.

{filteredList.map((item, index) => (
  <div key={index}>{item}</div>
))}
Enter fullscreen mode Exit fullscreen mode

Here's the complete code:

import { useState } from 'react';

export default function Home() {
  const [search, setSearch] = useState('');
  const [list, setList] = useState([]); // This should be your fetched list

  const filteredList = list.filter((item) =>
    item.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div>
      <input
        type="text"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="Search..."
      />

      {filteredList.map((item, index) => (
        <div key={index}>{item}</div>
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is a basic implementation and might need to be adjusted based on your specific use case and data structure. Hope this helps! Let me know if you have any other questions. 😊

Top comments (0)