DEV Community

monsterooo
monsterooo

Posted on

5 1

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?

😮

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (2)

Collapse
 
squgeim profile image
Shreya Dahal

Reminds me of AngularJS. :D

Collapse
 
monsterooo profile image
monsterooo

vue 😁

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay