ascendingDirectionSort has ‘true’ initial value. It can be changed by dropdownlist. When it is changed, console.log in the sortData function shows updated value, but only the ascendingDirectionSort==true condition executes, even when it’s false.
...Class
...constructor
this.state={
ascendingDirectionSort:true
}
render()...
const {ascendingDirectionSort}=this.state
const sortData(field)=>{
console.log(ascendingDirectionSort)//true, when ascendingDirectionSort=true and false when = false
if(ascendingDirectionSort){
execute1...//always executes
console.log(ascendingDirectionSort)
}else{
execute2...//doesnt work
}
}
...
<select value = {ascendingDirectionSort} onChange={this.handleChange}>
<option value={true}>Ascending</option>
<option value={false}>Descending</option>
</select>
...
handleChange = (event) => {
this.setState({ ascendingDirectionSort: event.target.value });
};Advertisement
Answer
<option value={true}>
While you are passing boolean values to the value props, they will be rendered as HTML attributes and so will be converted to strings.
if(ascendingDirectionSort){
You are testing the truthiness of the value of that variable.
true, "true" and "false" are all true values.
Use strings consistently.
this.state={
ascendingDirectionSort:"true"
}
and
if(ascendingDirectionSort === "true"){