karvai
karvai

Reputation: 1767

Using Boolean to filter instead of a ternary operator

I am passing in a style prop as follows which works fine as follows where I draw gradient colors
if $gradientProps is true.

Working copy

style={{
    backgroundImage: `url('${imageUrl}') ${
        $gradientProps
        ? `, linear-gradient(${
            $gradientProps.angle
            }, ${$gradientProps.colors.join()})`
        : ""
    }`
}}

But I am looking to NOT have to pass in that empty string when it is not available thus
going for the following. When I do this, I end up with an empty white space. Could I please check what I am doing wrong pls? Thanks.

What I am trying to do but end up with white background.

style={{
    backgroundImage: [
        `url('${imageUrl}')`,
        $gradientProps &&
        `linear-gradient(${
            $gradientProps.angle
        }, ${$gradientProps.colors.join()})`
    ]
        .filter(Boolean)
        .join(" ")
}}

Upvotes: 0

Views: 66

Answers (1)

Medi
Medi

Reputation: 1036

If the second parameter is null or undefined, you end up with a white background.

style={{
    backgroundImage:!gradientProps ? `url('${imageUrl}')`:
        `url('${imageUrl}'),
        linear-gradient(${
            $gradientProps.angle
        }, ${$gradientProps.colors.join()})`
}}

Upvotes: 1

Related Questions