JAmes
JAmes

Reputation: 281

More than one line of code in ternary statement?

Is it possible to have more than one "line of code" after the :? Currently, clearNameInputRef.current.style.display = "none"; is running regardless, but it should only run if searchName == ""/if searchName != "" is false

searchName != "" ? fetchClassesByName() : nameDropdownRef.current.style.display = "none"; clearNameInputRef.current.style.display = "none";

Upvotes: 2

Views: 383

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191728

Yes, you can add new-lines after ? or : for lines of code.

No, you cannot have multiple expressions inside the ": block".

Currently ... is running regardless

Because the semi-colon ended the ternary, and the else-expression.

You'd need to use a single expression in the else part, like a method.

searchName != "" ? fetchClassesByName() : ClearStyles(nameDropdownRef.current.style, clearNameInputRef.current.style);

...

private void ClearStyles(... s1 , ... s2) {  // Not sure what types these are
    s1.display = "none"; 
    s2.display = "none";
}

However, ternaries are meant to return a conditional value, not run two methods conditionally, so use an actual if-else.

Upvotes: 2

Related Questions