0

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.

1
  • 3
    You can't put if/elses straight into JSX but you can recreate the same logic with ternaries. However, it's better not to inline a bunch of logic like that, it mixes up the logic and view code and gets messy. Just have a function which determines which class name is apt, then have <div className={getTrackClassName(source)}> or something similar Commented May 7, 2019 at 5:26

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.