Search code examples
reactjsconditional-statementsreact-propsconditional-operator

Alternative to nested ternary expressions in my React component to pass prop value condionally


Based on a certain type field (from api) I have to conditionally send a string value through a prop to my React child component.

const labelOne = 'Label one';
const labelTwo = 'Label two';
const LabelThree = 'Label three';

return (

        <Child
          items={data?.items?.map((node) => ({
            labelText: node.type.includes('One')
              ? labelOne
              : node.type.includes('Two')
              ? labelTwo
              : node.type.includes('Three')
              ? LabelThree
              : '',
          }))}
        />
  );

But my Eslint doesn't like more then 2 ternary expressions.

Do not nest ternary expressions.

What is an alternative in this case?

Update:

I added a function:

const renderText = (type) => {
    let myText;

    switch (type) {
      case type.includes(Type.One):
        myText = 'Text one';
        break;
      case type.includes(TeaserType.Two):
        myText = 'Text two';
        break;
      case type.includes(TeaserType.Three):
        myText = 'Text three';
        break;
      default:
        break;
    }
    return ctaText;
  };

Then in my child component I have:

<Child myText: renderText(node.type) />

I am using typescript. For my myText prop I typed it like:

myText?: () => void;

But when I log it, it returns undefined?


Solution

  • step 1: define this function

    const typeQuery = (type)=>{ 
    switch (type) {
          case "Label one":
            return LabelOne
            break;
          case "Label two":
            return LabelTwo
            break;
          case "Label three":
            return LabelThree
            break;
          default:
            return null
            break;
        }
    }
    

    step 2: change the code like this

        <Child
              items={data?.items?.map((item) =>typeQuery(item.type) }
            />
    

    It may seem like a bit more work, but the syntax is much cleaner and much much more scalable if you get more types.