import { useState } from 'react';
const Shop = ({capes}: Props)=>{
const[checkVal1, setCheckVal1]= useState(0);
const[checkVal2, setCheckVal2]= useState(0);
const[checkVal3, setCheckVal3]= useState(0);
const[checkVal4, setCheckVal4]= useState(0);
const[checkVal5, setCheckVal5]= useState(0);
const handleCheckData=(cape:any)=>{
if(cape.price>=0 && cape.price>=checkVal1){
return 1;
}
else if(cape.price>=200 && cape.price<=checkVal2){
return 1;
}
else if(cape.price>=300 && cape.price<=checkVal3){
return 1;
}
else if(cape.price>=400 && cape.price<=checkVal4){
return 1;
}
else if(cape.price<= checkVal5){
return 1;
}
// else{
// return 1;
// }
}
return(
<div>
<div>
<div className='flex flex-col space-y-4'>
{/* 1st checkbox */}
<div>
<input type='checkbox' onClick={()=>setCheckVal1(199)} />
<label > {'>'} $1.99</label>
</div>
{/* 2nd checkbox */}
<div>
<input type='checkbox' onClick={()=>setCheckVal2(299)}/>
<label >$2.00 - $2.99</label>
</div>
{/* 3rd checkbox */}
<div>
<input type='checkbox' onClick={()=>setCheckVal3(399)}/>
<label >$3.00 - $3.99</label>
</div>
{/* 4th checkbox */}
<div>
<input type='checkbox' onClick={()=>setCheckVal4(499)}/>
<label >$4.00 - $4.99</label>
</div>
{/* 5th checkbox */}
<div>
<input type='checkbox' onClick={()=>setCheckVal5(500)}/>
<label > {'<'} $5.00</label>
</div>
</div>
This is the data I want to filter through by using checkboxes. Cape is another component and we retrieve a price from it eg 'cape.price or cape.name'.
Is there a way to filter them and we can reset them as well like if we click a checkbox it will show result and upon click again it will remove the price filter?
{capes.map((cape) => (
handleCheckData(cape) ?
<div
key={cape.id}
className='text-white transition duration-300 ease-in-out group hover:text-orange-500' >
<div className='flex flex-col items-center space-y-4 cursor-pointer'>
<div className='-ml-8 transition duration-300 ease-in-out group-hover:scale-110 transform-gpu'>
<RenderedMineman
capes={[cape]}
rotation={
cape.type ===
CapeTypeEnum.Cape
? 'back'
: 'front'
}
/>
</div>
<div className='space-y-1 text-center'>
<Text
as='h3'
tag='h3'
className='text-current'
>
{cape.name}
</Text>
</div>
<div className='space-y-1 text-center text-gray-700'>
<Text as='h4' tag='p'>
${toDollars(cape.price)}
</Text>
</div>
</div>
</Link>
</div>: ''
))}{' '}
</div>
)
}
CodePudding user response:
You could use the filter function on arrays before the map:
capes.filter((cape) => handleCheckData(cape)).map((cape) => (....