DEV Community

loading...

How to add a Search Bar in React

deboragaleano profile image Debora Galeano ・2 min read

This post will cover the following:

  • Simple steps on how to add a search bar in React
  • We'll use useState for managing the input text field
  • Filtering methods: filter and includes

Example:

Search Bar

Step 1: Add input tag

  • Add an input tag in the render area of your component. Attribute type should be set to text.
  • Now in order to set its value and add an onChange that will handle the value of our input, which is search in this case, we need to use useState
  • 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>
    )
Enter fullscreen mode Exit fullscreen mode

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>
    )
}
Enter fullscreen mode Exit fullscreen mode

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()))

Enter fullscreen mode Exit fullscreen mode

Step 3: Rendering and final code

  • In order to render the contacts that we're looking for, we now pass down the filteredContacts to the List 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>
    )
}
Enter fullscreen mode Exit fullscreen mode

Hope it was useful!

Note: my posts are inspired by what I'm learning at The Collab Lab ☺️

Discussion (13)

pic
Editor guide
Collapse
terrancecorley profile image
Terrance Corley

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.

Collapse
deboragaleano profile image
Debora Galeano Author

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.🤔

Collapse
terrancecorley profile image
Terrance Corley

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.

Collapse
zdev1official profile image
ZDev1Official

Amazing!
That helped me a lot!

Collapse
deboragaleano profile image
Debora Galeano Author

I'm glad it did. Thanks for letting me know! :)

Collapse
zdev1official profile image
ZDev1Official

Yes! No problem!

Collapse
theanamhossain profile image
Md. Anam Hossain

Awesome. Thanks for sharing.

Collapse
hajarnasr profile image
Hajar | هاجر

Awesome, Debora! ❤️

Collapse
deboragaleano profile image
Debora Galeano Author

Thanks so much, Hajar! ☺️

Collapse
brunowolf profile image
They Call Me Wolf

So simple. Perfect. Thanks a thousand.

Collapse
segdeha profile image
Andrew Hedges

Didn't know about Mockaroo. Very cool!

Collapse
femakin profile image
femakin

Thank you for this 😊 It really helped.

Collapse
yahaya_hk profile image
Yahaya Kehinde

Yes! Two articles down!. Great work 🎉🥳