Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 7, 2020 04:56 pm GMT

How to add a Search Bar in React

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


Original Link: https://dev.to/deboragaleano/how-to-add-a-search-bar-in-react-noc

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To