Reputation: 3433
I have 2 working functions that will allow me to sort by price high/low handleSortCheapest
and handleSortExpensive
, what I would like to do is combine these into 1 function handleSort
that will be called via an onCLick function and the parameter passed to it will determine whether it sorts high or low e.g onClick={()=> this.handleSort(high)}
I have attempted to write a function that will do this but it doesn't work so how can I create a function that will do this?
handleSortCheapest = () => {
this.setState({
sortValue: this.state.data.sort((a,b) => (parseFloat(a.price) - parseFloat(b.price)))
})
}
// Sort price high to low
handleSortExpensive = () => {
this.setState({
sortValue: this.state.data.sort((a,b) => (parseFloat(b.price) - parseFloat(a.price))),
})
}
handleSort = value => {
const low = this.state.data.sort((a,b) => (parseFloat(a.price) - parseFloat(b.price)))
const high = this.state.data.sort((a,b) => (parseFloat(b.price) - parseFloat(a.price)))
this.setState({
sortValue: value
})
}
onClick={()=> this.handleSort(high)}
onClick={()=>this.handleSort(low)}
Upvotes: 0
Views: 1439
Reputation: 2375
I'm guessing at what "doesn't work" means and I am assuming that the onClick
settings are part of JSX content such as within render()
. I also assume that data
is an array which is part of the object state.
One problem is that high
and low
are not valid outside the scope of the anonymous function assigned to handleSort
arrow-function. Even if this did work, I'd probably just use a boolean
parameter to handleSort()
rather than passing functions around.
handleSort = ascending => {
this.setState( {
sortValue: ascending
? this.state.data.sort((a,b) => (parseFloat(a.price) - parseFloat(b.price)))
: this.state.data.sort((a,b) => (parseFloat(b.price) - parseFloat(a.price)))
} )
}
Then invoke it within JSX render code:
render(
… onClick={() => this.handleSort(true)} … // ascending, low to high
… onClick={() => this.handleSort(false)} … // descending, high to low
)
Upvotes: 1