In this article, I learned a lot of knowledge, and combined with some experience in the work, I also thought about something. Such as conditional operators
Conditional Operator
condition ? expr_if_true : expr_if_false
When writing conditional statements in JSX, we often use the trinary operator (? : is also called the inline conditional operator. As you probably know, the ternary operator is not an intuitive way to write. Especially in complex situations.
Take the code in the article above for example 🌰
return (
<div>
<p>Text: {this.state.text}</p>
{
view
? null
: (
<p>
<input
onChange={this.handleChange}
value={this.state.inputText} />
</p>)}</div>
);
Copy the code
The above code displays a P element based on the view variable being false
Or display different elements or components as follows
return (
<div>
<p>Text: {this.state.text}</p>
{
view
? (
<p>
something value
</p>
) : (
<p>
<input
onChange={this.handleChange}
value={this.state.inputText} />
</p>)}</div>
);
Copy the code
The plethora of javascript ternary operators doesn’t look easy in JSX, and logical differentiation can get complicated at times
The situation gets even more complicated if you have some nesting (most ESLint does not use nesting)😓
return (
<div>
{ condition1
? <Component1 />
: ( condition2
? <Component2 />
: ( condition3
? <Component3 />
: <Component 4 />))}</div>
);
Copy the code
I’ve seen the code above and it’s like walking through a swamp to maintain
I was trying to figure out if I could abstract the conditional operators to a higher level 🤔 and then implement them using the React component.
I tried it and it worked, so I made something. The abstracted JSX conditional operation looks like this
Displays a component based on the value of a variable
<If when={this.state.logic}>
<p>↔️show component</p>
</If>
Copy the code
Same as above, but more readable, and logically and aesthetically superior to ternary operators
<If when={this.state.logic}> <p>↔️show component</p> <If when={this.state.logic}> <p> Other component</p> </If> </If>Copy the code
There are more options, and I should be able to see the code below without much explanation
<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>}/> {/* can provide a Default component */} </Switch>Copy the code
Iterate over an array or object
<For of={['a'.'b'.'c']} > {(item, index) = > (< p key = {index} > {index}, {item} < / p >)} < Default > Default component < / Default > {/ * can provide a Default component * /} < / a For >Copy the code
I created this repository for you to try
Do you have any ideas? Welcome to the discussion.
Thanks for reading 🙌