DEV Community

Discussion on: A React "if component"

Collapse
 
stereoplegic profile image
Mike Bybee • Edited

I personally think ternaries are fine, but expanding on your solution:

By adding a third else = null prop (and return else instead of return null), you can default to null while allowing for an actual value on the other side of the ternary e.g.

function IF({children, condition, else = null}) {
  if (condition) {
    // render children if the condition is truthy
    return children;
  }

  return else;
}

/**
 * Use the component as follows:
 *
 * <IF condition={condition}>
 *   <Greeter username={user.name} />
 * </IF>
 *
 * With 'else' prop, equivalent to
 * {condition ? <Greeter  username={user.name} /> : <LoginButton />}
 *
 * const renderElse = () => <LoginButton />
 * <IF condition={condition} else={renderElse}>
 *   <Greeter username={user.name} />
 * </IF>
 *
 *
 */
Enter fullscreen mode Exit fullscreen mode

You could even take it further with another prop, an array of objects in the shape of {extraCondition, extraReturn}, for else if scenarios (that's going to take too much typing to give an example of the additional logic on my phone, but I hope you get the gist).