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.
JavaScript
x
30
30
1
Class
2
constructor
3
this.state={
4
ascendingDirectionSort:true
5
}
6
render()
7
const {ascendingDirectionSort}=this.state
8
9
10
const sortData(field)=>{
11
console.log(ascendingDirectionSort)//true, when ascendingDirectionSort=true and false when = false
12
if(ascendingDirectionSort){
13
execute1//always executes
14
console.log(ascendingDirectionSort)
15
}else{
16
execute2//doesnt work
17
18
}
19
20
}
21
22
<select value = {ascendingDirectionSort} onChange={this.handleChange}>
23
<option value={true}>Ascending</option>
24
<option value={false}>Descending</option>
25
</select>
26
27
28
handleChange = (event) => {
29
this.setState({ ascendingDirectionSort: event.target.value });
30
};
Advertisement
Answer
JavaScript121<option value={true}>
2
While you are passing boolean values to the value
props, they will be rendered as HTML attributes and so will be converted to strings.
JavaScript121if(ascendingDirectionSort){
2
You are testing the truthiness of the value of that variable.
true
, "true"
and "false"
are all true values.
Use strings consistently.
JavaScript
1
4
1
this.state={
2
ascendingDirectionSort:"true"
3
}
4
and
JavaScript
1
2
1
if(ascendingDirectionSort === "true"){
2