DEV Community

karthikeyan
karthikeyan

Posted on • Updated on

simple search filter array of objects in javascrit (React js)

we are going to see how to filter the array of object when user type something in input field

first we take some mock data

  const  data = [
  {name:'karthi'},
  {name:'mani'},
  {name:'siva'},
  {name:'raj'}];
Enter fullscreen mode Exit fullscreen mode

add map the data first

{data.map((e)=>(
        <li>{e.name}</li>
      )
Enter fullscreen mode Exit fullscreen mode

after that we need to add filter function

{data.filter((e)=>e.name.toLowerCase().includes(searchtext.toLowerCase())).map((e)=>(
        <li>{e.name}</li>
      )
Enter fullscreen mode Exit fullscreen mode

so we have filter function now after that we need to get the user input text so we can use either usestate or useref here i am using usestate

 const handleinput = (e) => {
    console.log(e.target.value)
    setsearchtext(e.target.value)
  }
Enter fullscreen mode Exit fullscreen mode

thats all you got it

Full code :

import { useState } from "react";
import "./styles.css";

export default function App() {
    const  data = [
    {name:'karthi'},
    {name:'mani'},
    {name:'siva'},
    {name:'raj'}];
  const [searchtext, setsearchtext] = useState('');
  const handleinput = (e) => {
    console.log(e.target.value)
    setsearchtext(e.target.value)
  }
  return (
    <div className="App">
      <input
      placeholder="enter"
      onChange={handleinput}
      />
      {data.filter((e)=>e.name.toLowerCase().includes(searchtext.toLowerCase())).map((e)=>(
        <li>{e.name}</li>
      )
        )}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Discussion (0)