DEV Community

monsterooo
monsterooo

Posted on

better conditional operator than javascript itself

In this article, I've learned something but I'm also thinking about something.

Conditional Operator

Inline Conditional Operator is confusing example:

condition ? expr_if_true : expr_if_false

return (
  <div>
    <p>Text: {this.state.text}</p>

    {
      view
      ? null
      : (
        <p>
          <input
            onChange={this.handleChange}
            value={this.state.inputText} />
        </p>
      )
    }

  </div>
);
Enter fullscreen mode Exit fullscreen mode

Or display a component based on its variable value

{
  view
  ? null
  : (
    <p>
      <input
        onChange={this.handleChange}
        value={this.state.inputText} />
    </p>
  )
}
Enter fullscreen mode Exit fullscreen mode

If you have nested code 😰

return (
  <div>
    { condition1
      ? <Component1 />
      : ( condition2
        ? <Component2 />
        : ( condition3
          ? <Component3 />
          : <Component 4 />
        )
      )
    }
  </div>
);
Enter fullscreen mode Exit fullscreen mode

I wonder if I can abstract this statement as a react component?

Like this

<If when={this.state.logic}>
  <p>↔️show component</p>
</If>
Enter fullscreen mode Exit fullscreen mode
<If when={this.state.logic}>
  <p>↔️show component</p>
  <If when={this.state.logic}>
    <p>other component</p>
  </If>
</If>
Enter fullscreen mode Exit fullscreen mode

I think it's more beautiful and readable

There is a lot more

<Switch value={value}>
  <Case when={condition}>
    <p>condition 1</p>
  </Case>
  <Case when={condition}>
    <p>condition 2</p>
  </Case>
  <Case when='c' children={<p>condition 3</p>}/>
  <Default children={<p>default component</p>}/>
</Switch>
Enter fullscreen mode Exit fullscreen mode

Determines multiple conditions and can display default components

Iterate through the traversal array or object

<For of={['a', 'b', 'c']}>
  {(item, index) => (<p key={index}>{index}{item}</p>)}
  <Default>default component</Default>
</For>
Enter fullscreen mode Exit fullscreen mode

I created a repo for this

Do you have any ideas?

😮

Top comments (2)

Collapse
 
squgeim profile image
Shreya Dahal

Reminds me of AngularJS. :D

Collapse
 
monsterooo profile image
monsterooo

vue 😁