Search code examples
javascriptastrojs

Astro renders "0" instead of html


For a language switcher if have this condition:

{
    !isArticleLink ? (
        <a
            href={href}
            class:list={[cn(className, { 'border-b-4 border-regalblue pb-2': isActive })]}
            {...props}
        >
            {language}
        </a>
    ) : (
        (
            <a
                href={`/en/blog/${postNL?.data.translation}`}
                class:list={[cn(className, { 'border-b-4 border-regalblue pb-2': isActive })]}
                {...props}
            >
                EN
            </a>
        ) |
        (
            <a
                href={`/nl/blog/${postEN?.data.translation}`}
                class:list={[cn(className, { 'border-b-4 border-regalblue pb-2': isActive })]}
                {...props}
            >
                NL
            </a>
        )
    )
}

Based on whether is a link for a blogarticle or not, it renders a different link. When isArticleLink is false, works fine, it outputs "NL|EN". However when isArticleLink is true it outputs "0|0".

I checked the postEN and postNL objects and both refer to the right object, so I don't know what's causing this issue.

Does anyone know what's going on, or have you had the issue in your Astro code?


Solution

  • You're accidentally using the bitwise OR operator (|) between two JSX elements. The bitwise OR of two non-numeric values is 0 ('a' | 'b') === 0. The correct syntax you're looking for is a JSX Fragment:

        <>
            <a
                href={`/en/blog/${postNL?.data.translation}`}
                class:list={[cn(className, { 'border-b-4 border-regalblue pb-2': isActive })]}
                {...props}
            >
                EN
            </a>
            |
            <a
                href={`/nl/blog/${postEN?.data.translation}`}
                class:list={[cn(className, { 'border-b-4 border-regalblue pb-2': isActive })]}
                {...props}
            >
                NL
            </a>
        </>