Search code examples
javascriptreactjsconditional-rendering

Trying to display different value depending on other values in React


I have this conditional rendering

      {livematchcard.event.status_name != "Ολοκληρώθηκε" ? "Τελικό"

                            : (livematchcard.event.sport_id == 4 ? (
                                (livematchcard.event.status_id == 134 ? livematchcard.periods[0] : null)
                                (livematchcard.event.status_id == 65 ? livematchcard.periods[1] : null)
                                (livematchcard.event.status_id == 135 ? livematchcard.periods[2] : null)
                                (livematchcard.event.status_id == 136 ? livematchcard.periods[3] : null)
                                (livematchcard.event.status_id == 137 ? livematchcard.periods[4] : null)
                            ) : livematchcard.event.clock_time)
                        }

So, the problem is that I can see the clock time where I should but if a condition inside is met for example is status_id is 134 I get the following error which I cannot seem to understand Uncaught TypeError: (intermediate value)(intermediate value)(intermediate value) is not a function. I also tried to change the code to this livematchcard.event.status_id == 134 && livematchcard.periods[0] where I get the following error

livematchcard.periods[0] is not a function


Solution

  • The error you're encountering is related to the structure of your ternary conditional expressions.

    In JSX, when you have complex expressions within JSX curly braces, it's important to make sure you're using the correct syntax. You can't directly chain multiple ternary expressions together like you're attempting to do.

    To achieve your desired conditional rendering, you can modify your code as follows:

    {
      livematchcard.event.status_name !== "Ολοκληρώθηκε"
        ? "Τελικό"
        : livematchcard.event.sport_id === 4
        ? livematchcard.event.status_id === 134
          ? livematchcard.periods[0]
          : livematchcard.event.status_id === 65
          ? livematchcard.periods[1]
          : livematchcard.event.status_id === 135
          ? livematchcard.periods[2]
          : livematchcard.event.status_id === 136
          ? livematchcard.periods[3]
          : livematchcard.event.status_id === 137
          ? livematchcard.periods[4]
          : null
        : livematchcard.event.clock_time
    }
    

    In this code snippet, I've properly nested the ternary expressions to achieve the desired conditional rendering. Make sure to carefully match opening and closing parentheses and curly braces.