Here's a simple way to add search 🔎 functionality in Next.js.
Preview 🪟:
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 ... }
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..." />
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()) );
Finally, map through your filteredList
to display the items.
{filteredList.map((item, index) => ( <div key={index}>{item}</div> ))}
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> ); }
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. 😊
Stay Connected and Get More Insights
If you find this guide helpful and are dealing with similar challenges, feel free to reach out to me at https://ayushrudani.com. For more tech insights and updates, consider following me on GitHub. Let's innovate together!
Top comments (0)