skip to Main Content

Looking for a cleaner way to render and change icon size basic on if my size prop is undefined or if a value is provided

example if props.size is undefined the size should be 30 however if props.size is equal to 20 then the icon will have a size of 20

works

<TheIcon name={props.iconName} size={props.size ? props.size : 30} />

Would the below code work or do the same. I am looking for a cleaner way to do the code above

<TheIcon name={props.iconName} size={props.size ?? 30} />

2

Answers


  1. No that is a nullish operator and does not at all behave as the ternary operator.

    For more:
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

    Login or Signup to reply.
  2. You can do something like this if props.size == undefined then harder coded value 30 else use the size.

    <TheIcon name={props.iconName} size={props.size == undefined ? 30 : props.size} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search