This post will cover the following:
- Simple steps on how to add a search bar in React
- We'll use
useState
for managing theinput
text field - Filtering methods:
filter
andincludes
Example:
Step 1: Add input tag
- Add an
input
tag in the render area of your component. Attributetype
should be set to text. - Now in order to set its
value
and add anonChange
that will handle the value of our input, which is search in this case, we need to useuseState
- The
onChange={(e) => setSearch(e.target.value)}
will set the search every time it changes - Now our input value is managed by our state!
- Next we'll see how we can filter our
contacts
array
export default function Search() {
const [search, setSearch] = useState('')
return (
<div>
<h3 className="title">CONTACTS LIST</h3>
<input
type="text"
placeholder="Search name"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
//a contacts array passed down to List
<List contacts={contacts/>
</div>
)
List.js
component
export default function List({contacts}) {
return (
<div>
<ul>
{contacts.map(contact => (
<li key={contact.id}>
Name:
<span>{contact.full_name}</span>
Phone:
<span>{contact.tel}</span>
</li>
))}
</ul>
</div>
)
}
Step 2: Adding the search functionality!
This is what we're telling filteredContacts
to do:
- If we haven't searched for anything yet, please just show the contacts list
- If not, please filter the contacts array and check that every contact's full name includes in the search field that we're looking for
- And, if we type in lowercase, please don't mind it so much and still show us the results :)
const filteredContacts = search.length === 0 ? contacts
: contacts.filter(contact =>
contact.full_name.toLowerCase().includes(search.toLowerCase()))
Step 3: Rendering and final code
- In order to render the contacts that we're looking for, we now pass down the
filteredContacts
to theList
component (see below) - This is the entire code for the
Search
component
Note: For the fake data, I'm using a Mockaroo API, as well as axios
inside useEffect
.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
import List from './List';
export default function Search() {
const [contacts, setContacts] = useState([])
const [search, setSearch] = useState('')
useEffect(() => {
const API_URL = 'https://my.api.mockaroo.com/phonebook.json?key=9ac1c5f0'
axios
.get(API_URL)
.then(res => {
const contacts = res.data
setContacts(contacts)
})
}, [])
const filteredContacts = search.length === 0 ? contacts :
contacts.filter(contact => contact.full_name.
toLowerCase().includes(search.toLowerCase()))
return (
<div>
<h3>CONTACTS LIST</h3>
<input
type="text"
placeholder="Search name"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<List contacts={filteredContacts}/>
</div>
)
}
Hope it was useful!
Note: my posts are inspired by what I'm learning at The Collab Lab βΊοΈ
Top comments (13)
Awesome post! Iβm curious, would it be better to manage the filtered list in state? Wondering if itβs βbest practiceβ to pass a list as a prop down that isnβt being managed by state.
Hi Terrance, thanks for your message! The contacts list is actually being managed by state and passed down as props. The difference is that it's conditionally doing so through the filteredContacts (so if there's no search, contacts list will be passed down as is, if not, it will passed down same list but filtered). Not sure if I'm answering your question.π€
Yeah! Makes perfect sense. The thing I noticed is you pass down filteredContacts, not contacts, so you never have the filtered list of contacts in state. Thatβs the part I was curious about if itβs βbest practiceβ or not. I do see that filteredContacts is created from contacts, but filteredContacts just lives in a variable that is passed as a prop, itβs not actually a part of your state. I donβt know if that really matters though. Regardless, awesome post! Keep emβ coming.
Amazing!
That helped me a lot!
I'm glad it did. Thanks for letting me know! :)
Yes! No problem!
Awesome. Thanks for sharing.
Awesome, Debora! β€οΈ
Thanks so much, Hajar! βΊοΈ
So simple. Perfect. Thanks a thousand.
Didn't know about Mockaroo. Very cool!
Thank you for this π It really helped.
Yes! Two articles down!. Great work ππ₯³