I read QA in stackoverflow, but not described about how to setup controlled single and multiple in same time,
i have a multiple filter, but sometime use can select only one or more, when we come to our react form
handleChange = (e) => {
const target = e.target;
const value = target.value;
const name = target.name;
this.setState({[name]:value})
this.props.onChange({[name]:value})
}
..................
carPrice:
<input
name="carPrice"
type="text"
value={this.state.carPrice}
onChange={this.handleChange}/>
price_category :
<select
name="price_category"
value={this.state.price_category}
onChange={this.handleChange} >
<option >Select</option>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
Here is the form, user can select one or more filter same time. the output looks like when user give input
{price_category: "low"}
if give car Price
{ carPrice: "20000"}
Filter here
Here we are filter the sate,
f = (filterparams)=>{
//filterparams ---> {price_category: "low"}
let filtercars = this.state.cars // car array here
filtercars = filtercars.filter
(
car=> {return car.carPrice <= filterparams.carPrice ||
car.price_category === filterparams.price_category }
)
this.setState({
filtercars
})
}
Issue
- selecting car rate 5000, its show car under the price = work fine
- then selecting price category high, shows car under 5000 and high = work fine
- then selecting car rate 1000, shows all cars from price category high = not working
Edit
render() {
return (
<div>
<CarResult cars={this.state.filtercars} onChange={this.f}/>
</div>
)
}
f(filterparams)is used.categoryis reset every time you set aprice. just check yourpriceHandlerand set thecategorythere too