chandra
chandra

Reputation: 45

How to write Nested if else in react js

I am trying to implement nested if else in react compound slider. I am able to write if else using ternary operator and that is working fine

<div className={source.value >.3 ? 'greater': 'lesser'}>
   <Track
     key={id}
     source={source}
     target={target}
     getTrackProps={getTrackProps}
     />
</div>

so here i am able to check only condition whether it is greater than .3 or less than but am trying to implement

if(source.value <.3)
{
return classNameFirst
}
else if (source.value >.3 && source.value <.7){
return classnameSecond
}
else if (source.value >.7 && source.value <.9){
return classnamethird
}
else if (source.value >.9 && source.value <1.2){
return classnameFourth
}
else{
return classnamefive
}

how can i implement this thing into my jsx code.

Thanks in advance.

Upvotes: 0

Views: 265

Answers (3)

Utsav Patel
Utsav Patel

Reputation: 2899

Define a function in your helper or utility file. You can also define the function in your class itself, but generally it is a good idea to use helper file for this.

So you can have a function getTrackClass which will accept source.value as the parameter and return you the appropriate class.

getTrackClass = value => {
  if (value < 0.3) {
    return classNameFirst;
  } else if (value > 0.3 && value < 0.7) {
    return classnameSecond;
  } else if (value > 0.7 && value < 0.9) {
    return classnamethird;
  } else if (value > 0.9 && value < 1.2) {
    return classnameFourth;
  } else {
    return classnamefive;
  }
};

After this you can use this function to get the class for your Track component.

<div className={this.getTrackClass(source.value)}>
   <Track
     key={id}
     source={source}
     target={target}
     getTrackProps={getTrackProps}
     />
</div>

Upvotes: 2

cbdeveloper
cbdeveloper

Reputation: 31495

Is this what you're trying to accomplish?

return(
  source.value < .3 ?
    classNameFirst
  : source.value < .7 ?
      classNameSecond
      : source.value < .9 ?
          classNameThird
          : source.value < 1.2 ?
              classNameFourth
              : classNameFive
);

Upvotes: 0

Dinesh Verma
Dinesh Verma

Reputation: 666

Use the package named classNames in your application.

https://www.npmjs.com/package/classnames

This will give you the flexibility of using multiple classes, but will also allow you to use classes conditionally in a more readable way.

Upvotes: 0

Related Questions