6

As in doc it should be possible to set style classes for #[Lightning] components using a Ternary operator.

<div class="{!v.IsTest ? '' : 'slds-hide'}">test</div>

But it seems when I do so, getting error in component loading as,

SyntaxError: JSON.parse: unexpected keyword at line 320 column 42 of the JSON data

Above error is thrown from Aura framework.

There is a workaround for this (using init event),

Any thoughts on this (Have you got a similar issue, or what could lead to this). Thx.

4
  • I use Ternary operator in the class property all the time. What is the line of markup that is causing you the issue?
    – Eric
    Commented May 10, 2017 at 0:01
  • @Eric Thanks. Updated above. Even if I use the same syntax in doc example, it appeared. My component is bit complex too. But only this single code line could break it and stop loading the whole page. Commented May 10, 2017 at 0:29
  • 1
    I copied and pasted that markup <div class="{!v.IsTest ? '' : 'slds-hide'}">test</div> into one of my component and it worked without issue. Just FYI to confirm in a general sense that it works as expected
    – Eric
    Commented May 10, 2017 at 0:43
  • @Pasan Eeriyagama, consider accepting any below answer if they helped answer your post. Thanks
    – glls
    Commented Jan 29, 2018 at 18:30

2 Answers 2

9

You really should be using aura:if for rendering elements:

<aura:if isTrue="{!v.IsTest}"><div>test</div></aura:if>

You don't need to compare a Boolean value to true, it's already true. That said, the following should also work:

<div class="{!v.IsTest? '': 'slds-hide'}">test</div>
3
  • 1
    Thanks. I need to toggle the style class within component, and It's not recommended to use Aura:if for the toggle as in doc. The second one gave me the JSON error, so I tried different syntax options. Unfortunately getting same error. Commented May 10, 2017 at 0:41
  • 1
    @PasanEeriyagama Something else is throwing off your code. I realize that you think it's "this" particular line, but I've used it numerous times without fail. You might need to show off more of your code (preferably something that we can copy-paste to reproduce in our own org).
    – sfdcfox
    Commented May 10, 2017 at 0:49
  • @sfdcfox, it is working perfectly. Commented Aug 19, 2019 at 14:03
3

There must be something else which is causing the issue. I am assuming test is of type Boolean.

Just to verify, I created a sample component and ternary expression, it worked fine. Below is the sample code

<aura:component >
    <aura:attribute name="test" type="Boolean" default="true" />
    <div class="{!v.test?'no-hello':'hello'}" /> 
</aura:component>

Here are the alternative ways you can do it:

  • By using if function within the expression

< div class="{! if ( v.test, 'no-hello' , 'hello' ) }" />

  • By using Aura:if

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .