DEV Community

Cover image for Real Time Searching In ReactJS
ShubhamTiwari909
ShubhamTiwari909

Posted on

Real Time Searching In ReactJS

Hello Guys today I am going to show you how to search element in React in Real Time without clicking a button. The Search will be Real time , when you type a word then all the elements containing that word will be filtered and showed to you .

I have used a sample data for this code, You can use your data for this code as well.

Data -

const Data = [

        {
          "id": "61050f211ab57ba6cd86b1e8",
          "name": "Valeria Ramos"
        },
        {
          "id": "61050f21aa707624a853421b",
          "name": "Campos Daniels"
        },
        {
          "id": "61050f21ec0c4d434eedda85",
          "name": "Kate Gilbert"
        },
        {
          "id": "61050f21a4543be9235f4643",
          "name": "Hunt Lynch"
        },
        .
        .
        .
        .
        .
    ];
Enter fullscreen mode Exit fullscreen mode

Code for Searching -

import React,{useState} from 'react'
import Data from './SampleData'
import './App.css';

function App() {

    const [list, setList] = useState("");


    return (
        <div className="text-center my-5">
            <input 
            type="text"
            placeholder="search..."
            onChange={(event) => {
                setList(event.target.value);
            }}
            />

            <div  className="main">
                {Data.filter((item) => {
                    if(list === ""){
                        return item;
                    }
                    else if(item.name.toLowerCase()
                            .includes(list.toLowerCase())){
                        return item
                    }

                }).map((item) => (
                    <div key={item.id}><p className="items"> 
                      {item.name}
                    </p></div>
                ))
                }
            </div>
        </div>
    )

}

export default App;
Enter fullscreen mode Exit fullscreen mode

Working -

  1. First we created a state for the input element using useState.
  2. Then we created an input element using input tag and inside it we have onChange event and inside onChange we change the state of the list matching to the word typed in the input field.
  3. Then we filtered the Data using Filter method. 4.if(list===""){ return item;} , it means if the input field is empty, then return the whole data.
  4. else if(item.name.toLowerCase().includes(list.toLowerCase())){ return item } It first convert the name to lowercase using toLowerCase() method then it checks that the typed word is included in the Dataset or not using included() method and also it converts the input word in to lowercase using toLowerCase() method because the names are also in lowercase format.
  5. Then after filtering the data, we mapped the data using map() method

CSS -

p{
  border-radius: 50%;
  width: 150px;
  height: 150px;
  background-color: crimson;
  display: flex;
  justify-content: center;
  align-items: center;
  color: antiquewhite;
}
.main{
  margin: 5rem;
  display: grid;
grid-template-columns: repeat(4,1fr);
justify-content: center;
text-align: center;
}
Enter fullscreen mode Exit fullscreen mode

Output -

Before Searching

Screenshot (4)

After Searching

Screenshot (5)

Hope you understand the process and if there is any mistake please mention it in the comment section. It will help me also to know my mistakes so that i can fix it.

THANK YOU FOR READING THIS POST

Discussion (7)

Collapse
vu profile image
Vu

As I see, it's not real time.
What happen when you have lots of items, you need request the server to get them, so it will request every time you enter a character.
I think you should research a bit about 'debouncing' and ''managing server state"

Collapse
ats1999 profile image
Rahul kumar

Instead of denounce we can also use onBlur to request server.

Collapse
shubhamtiwari909 profile image
ShubhamTiwari909 Author

I don't know about fetching data from server and other server states , Its just a front-end part with Some JSON data
I will learn other topics later

Collapse
danwood profile image
Dan Wood

You can simulate it using Promise with a setTimeout.

Collapse
lukeshiru profile image
LUKESHIRU

Remeber to set the value attribute of input to match the currentState:

<input
    onChange={event => setList(event.currentTarget.value)}
    placeholder="search..."
    type="text"
    value={list}
/>
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
nphamvn profile image
nphamvn

The most important is data is got from server. But you store data in a variable.

Collapse
shubhamtiwari909 profile image
ShubhamTiwari909 Author

Its About logic here only that's why I used the data in a variable