How to add a Search Bar in React 
Tags: react, javascript, webdev
Published: 2020-11-07 16:56:26

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](https://dev-to-uploads.s3.amazonaws.com/i/r2ko5r57c69ankogi25e.gif)

### 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 


```javascript 
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 

```javascript 
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 :) 

```javascript 
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 the `List` component (see below)
- This is the entire code for the `Search` component 

**Note**: For the fake data, I'm using a [Mockaroo](https://www.mockaroo.com/) API, as well as `axios` inside `useEffect`.  

```javascript 
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](https://the-collab-lab.codes/who-we-are/) ☺️