2

I want to show only one data using search() and filter() but its showing error in runtime that it's not a function below is my code please help me out. By the way I am new to reactJS so I don't know much about it. Thank you.

Here I have created the search bar using CSS and HTML code.

<input style={{marginTop:'50px',}} type="text" name="search" id="search" onChange={(e)=>{setSearch(e.target.value)}} placeholder='search by post id'/>

Below is the code that I want to use for searching data through post_id from the JSONPlaceholder

  {

           search.filter((val)=>{
             if(search=='')
             {
               return val
             }
             else if(val.title.toLowerCase().includes(search.toLowerCase())){

             }
           }).map((val,key)=>
           {
            return(
             <div className="col-md-3 animated fadeIn " key={key}>
            <div className="card" style={{padding:'10px'}}> 
               <center><h5 className='card-title card-text p-3 mb-2 bg-danger text-white'>Post no.:- {val.id}</h5></center> 
               <div className="card-body"> 
                 <div className="avatar"> 
                   <img 
                     src={val.thumbnailUrl}
                     className="card-img-top"
                     alt=""
                   />
                 </div> 
                 <p className="card-text p-3 mb-2 bg-success text-white"> 
                  <span></span>  
                   <br /> 
                   <h6 className="">Title:{val.title}</h6> 
                 </p> 
               </div> 
               <div> 
                  <center><button onClick={e=>{commentClick(e)}} className="btn btn-primary btn-sm" >Comments</button></center>  
               </div> 
             </div> 
           </div> 
            ) 
           })
        }
    

setSearch() is State that I am using

const [search, setSearch] = useState('');

edit: Here I am searching by using title not post_id please ignore the above placeholder in <input/>.

  • 1
    as i am seeing, your search state is a string (e.target.value) and not and array. but you are using "val.title" in your filter function which is logically available on an objects. it should give u run time error and it is logical. – Ehsan Aug 27 '22 at 18:17
  • 1
    Can you show all the relevant code please? – Youssouf Oumar Aug 27 '22 at 19:39

0 Answers0