javascriptreactjsor-condition

reactjs OR condition breaks in the second comparison


I'm trying to add different Id to a component based on a certain value.

My approach is like below

id={activePage === ('dashboard' || 'evc_detail')? 'bg_gradient':'bg_normal'}

In this scenario if the activePage is equal to dashboard the correct id is added but it does not register if activePage is equal to evc_detail. Is the way i'm using this condition wrong and how can i solve this?


Solution

  • If you want to multiple comparisons you'll need to state them manually:

    (activePage === 'dashboard' || activePage === 'evc_detail') ? 'bg_gradient' : 'bg_normal'
    

    Another option is create an array of items (or a Set), and use Array.includes() (or Set.has) to check if an item is in the group:

    const gradientPages = ['dashboard', 'activePage']
    
    gradientPages.includes(activePage) ? 'bg_gradient' : 'bg_normal'
    

    Your original expression activePage === ('dashboard' || 'evc_detail')? 'bg_gradient':'bg_normal' doesn't work if the activePage is not 'dashbarod' because of the way it's evaluated:

    1. 'dashboard' || 'evc_detail' is evaluated, since 'dashboard' is a truthy expression, the result is always dashboard.
    2. 'dashboard' is compared with activePage. If activePage is 'dashboard' the result is true, if not it's false.