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'}];
add map the data first
{data.map((e)=>(
<li>{e.name}</li>
)
after that we need to add filter function
{data.filter((e)=>e.name.toLowerCase().includes(searchtext.toLowerCase())).map((e)=>(
<li>{e.name}</li>
)
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)
}
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>
);
}
Top comments (0)