AnApprentice
AnApprentice

Reputation: 110950

How do I set className based on three conditions?

I currently have the functional component:

let renderEmailField = ({input, label, type, meta: {touched, error, pristine}}) =>
    <fieldset className=????
     .....

I currently am using this ternary expression to conditionally add a class:

<fieldset className={touched ? (error ? "has-danger" : "has-success") : ""}>

The problem with the above is it does not take into account the new pristine prop, where if pristine is true, then "has-success" should not be added since the user hasn't done anything.

How can I update the above className logic, to only add "has-danger" or "has-success" if pristine is false?

Upvotes: 1

Views: 629

Answers (2)

Andrew Li
Andrew Li

Reputation: 57934

I agree that using ternary operators isn't the best. You could set it with some if statements, but I find a much cleaner way with the classnames package, which can also be inline. Currently, the code you have now would look like this with classnames:

<fieldset className={classNames({
  "": !touched && !error,
  "has-danger": touched && error,
  "has-success": touched && !error
})}>
  ...
</fieldset>

You could change the conditions for "has-danger" and "has-success" to account for pristine like so:

<fieldset className={classNames({
  "": !touched && !error,
  "has-danger": !pristine && touched && error, //you could cache !prinstine && touched as to not have duplicate code
  "has-success": !pristine && touched && !error
})}>
  ...
</fieldset>

For each potential class to add, you describe a certain condition for it to be added. If touched is truthy and error is falsey, then add no class. If not pristine, and touched, and error, then "has-danger" is added. If not pristine, and touched, and no error, then add "has-success". You could even get rid of the first condition because it's a tad useless and add your own cases.

Upvotes: 1

Mayank Shukla
Mayank Shukla

Reputation: 104369

I think, writing multiple conditions using ternary operator is not a good idea, what you can do here is simply call a function and put if-else conditions inside that and return the class name from that function.

Like this:

<fieldset className={this._setClassName()}/>

_setClassName(){
    if()
       return "a";
    else if()
       return "b";
    else
       return "c";
}

For Functional components, use {}, put all the logic for class name and use that with fieldset element.

Like this:

let renderEmailField = ({input, label, type, meta: {touched, error, pristine}}) => {
     let className = "";
     if()
        className = "a";
     else if()
        className = "b";
     else
        className = "c";

     return(
         <fieldset className={className}/>
     )
}

Upvotes: 2

Related Questions