When I have more than 2 options for conditional style in React, I'd rather not have ternary conditions within ternary conditions, so I use a self-invoking function like this:
const HeaderLink = ({
label,
linkTo,
firstItem = false,
lastItem = false,
}: {
label: string;
linkTo: string;
firstItem?: boolean;
lastItem?: boolean;
}) => {
return (
<div
id="HeaderLink"
style={{
padding: (() => {
if (firstItem) return "0 1vw 0 0";
if (lastItem) return "0 0 0 1vw";
return "0 1vw";
})(),
}}
>
<Link href={linkTo}>{label}</Link>
</div>
);
};
It works, but is there a smarter way? Are there reasons to avoid this pattern?
But even if you won't, even in that case you might want to have an easy time reading your code and define the function only once. Instead of a self-invoking function, you may create a function, like
function getWV(firstValue, secondValue) {
alert("I have been executed");
//...do your stuff
}
//proof-of-concept
getWV('a', 'b');
The example above shows that you can achieve a one-liner in your rendering code, only calling the function instead of defining it each time you render it and obscuring the readability of the renderer.
let array = ["0 1vw 0 0", "0 0 0 1vw", "0 1vw"];
function getItem(items)
{
let filteredArray = items.filter((item) => !!item);
if (filteredArray.length) return array[items.indexOf(filteredArray[0])];
return array[items.length];
}
console.log(getItem([null, 3]));
console.log(getItem([null, 0]));
At first sight this code may not appear much better than yours, but imagine the case when you may have more than two values. In that case you would have as many if conditionals as many items, while the approach above is much more dynamic.