ReactJs SyntaxError with ternary operator - javascript

Below code shows syntax error in ReactJs component:
(that.props.actionType == "opinion")
?
{that.state._CmtCnt?<ViewAnswer isFullView={that.props.isFullView?true:false} />:null}
:
{that.state._CmtCnt?<ViewComment isFullView={that.props.isFullView?true:false} />:null}

Basic Syntax is:
condition? expression1 : expression2
This is because you are using {} with expression1 and expression2, remove that, {} is required when we want to put JS expressions inside JSX. The way you are using, it means you are trying to return an object and error is because key is not valid.
Write it like this:
(that.props.actionType == "opinion") ?
(that.state._CmtCnt?<ViewAnswer isFullView={that.props.isFullView?true:false} />:null)
:
(that.state._CmtCnt?<ViewComment isFullView={that.props.isFullView?true:false} />:null)

You need to use normal parenthesis for grouping. Braces work only within jsx expressions.
that.props.actionType == "opinion"
? (that.state._CmtCnt ? <ViewAnswer isFullView={that.props.isFullView} /> : null)
// ^ ^
: (that.state._CmtCnt ? <ViewComment isFullView={that.props.isFullView} /> : null)
// ^ ^

You should write easier to understand code rather than complex nested terinary with little changes between them - all you choose is pick up a component to use, so move that up and you end up with easier to read code with less logic inside JSX
const Renderer = that.props.actionType == "opinion" ? ViewAnswer : ViewComment
// ...
{that.state._CmtCnt && <Renderer isFullView={!!that.props.isFullView} />}
// or
{that.state._CmtCnt ?
<Renderer isFullView={!!that.props.isFullView} /> :
null
}
not sure why you are using that either - aliases for context such as self or that are a bit out of date, you tend to want to keep context to your instances and bind correctly

Related

Can i use multiple line in ternary operator

I want to use the if else statement in the ternary operator
if (open) {
setOpen(false)
} else {
setOpen(true)
navigator.clipboard.writeText(link)
}
There is no problem in "if" I cant figuring out how to convert else to ternary. Like something the code below:
open ? setOpen(false) : setOpen(true) ; navigator.clipboard.writeText(link)
Something like this or is there another method to do the job?
Don't.
You're trying to use the ternary conditional operator for the wrong reason. It is not a drop-in replacement for any if block.
The ternary conditional operator is an expression. It resolves to a value, which can be used elsewhere. For example:
let x = someCondition ? 1 : 0;
The expression resolves to a value, either 1 or 0, and that value is used in an assignment statement.
The code you're showing is not an expression. What you have is a series of statements, conditionally executed based on some value. An if block is a structure for conditionally executing statements.
The code you have now is correct.
Yes, it's possible to write multiple statements in ternary if else cases:
The format is:
condition ? codeLine1 : ( codeLine2 , codeLine3 )
Which makes your statement as:
open ? setOpen(false) : (setOpen(true), navigator.clipboard.writeText(link));
Combine multiple statements in parenthesis separated by commas in between each line.
That being said it's recommended to use old fashioned way of if-else statement if multiple statements are involved.
Please select answer if it helps and let me know if any questions.
Yes. it is possible (although not a best practice and not recommended)
they way to to it is by:
Put everything inside parenthesis
Seperate each statement with comma (",")
e.g:
condition ? statement1 : ( statement2, statement3, statement4 )
Try this snippet:
let a = 1;
let b = 1;
a == b ?
(console.log("they"),console.log("are"), console.log("equal")) :
(console.log("they're"), console.log("not equal"));

Better way to write ngClass condition

I am trying to think of a cleaner way to write this condition:
[ngClass]="{
'class1':
image.isAvailable && (image.property !== true && !null),
'class2':
image.isAvailable && (image.property === true && !null)
}"
So image.property sometimes can be NULL, and I am trying to handle it...I know I'm missing something obvious but don't know what. Any help much appreciated
You could use safe navigation operator ?. with ternary operator.
[ngClass]="(image?.isAvailable && image?.property) ? 'class1' : 'class2'"
Safe navigation operator checks if a property is defined before trying to access it.
Update
OP's requirement - use neither of the classes if image?.isAvailable is undefined.
You could extend the ternary operator to one more level to check if image?.isAvailable is defined before applying the classes.
[ngClass]="image?.isAvailable ? (image?.property ? 'class1' : 'class2') : ''"
The empty string '' denotes empty class list if image?.isAvailable property is undefined.
This can be written like this:
[ngClass]="{
'class1':
image.isAvailable && !image.property),
'class2':
image.isAvailable && image.property)
}"
Also you can write like this:
[class.class1]="image.isAvailable && !image.property"
[class.class2]="image.isAvailable && image.property"

How do i use nested ternary operator in my code? Javascript

Trying to use nested ternary operator in my code
Code:
let ele_Partition = records[0].data.meeting ?
records[0].data.meeting.partition : records[0].data.partition;
Need to add another data for the same condition.
records[0].data.meeting.meetingPartition
How to implement it without nested if-else?
let ele_Partition = records[0].data.meeting ?
records[0].data.meeting.partition : records[0].data.meeting.meetingPartition ?
records[0].data.meeting.meetingPartition : records[0].data.partition;
If records[0].data.meeting, set the variable to records[0].data.meeting.partition.
Else if records[0].data.meeting.meetingPartition, set the variable to records[0].data.meeting.meetingPartition
Else set the variable to records[0].data.partition.
You should avoid nested ternary operators as they make your code incredibly complicated to read.
I would take a single ternary with a default value
let ele_Partition = records[0].data.meeting
? records[0].data.meeting.partition
: records[0].data.meeting.meetingPartition || records[0].data.partition;

button.js in ternary operator code

I was just looking up the code in button.js and I saw this ternary operator that's hard to decode. Basically I am talking about the below line of code:
$el[val](data[state] == null ? this.options[state] : data[state])
I understand the below part:
data[state] == null ? this.options[state] : data[state]
But what is this:
$el[val]
I am having a problem understanding this javascript syntax, can somebody decode the complexity and explain this to me please. I ran through the code a few times, but still couldn't quite understand.
You can check out the plugin on GitHub too, here's the link : link (line 40)
On line 31, you can see this line
var val = $el.is('input') ? 'val' : 'html'
val and html functions of jQuery object. So, $el[val] returns a function reference of either val or html, which is called by passing the result of
data[state] == null ? this.options[state] : data[state]
To be more clear,
var func = $el[val]; // function reference is gotten
func(data[state] == null ? this.options[state] : data[state]); // invocation
The above is just to show how it works. In real time it would break, as context of $el is missing.

Ternary Operator in JavaScript With Multiple Expressions?

the_styles ? the_styles.appendTo('head'); the_styles=null : the_styles = $('.stylesheet').detach();
Obviously, this isn't valid. Notice the ";" between the appendTo() and the_styles=null. How do I write it on 1 line and still have multiple expressions like that?
Use the comma operator this way:
the_styles ? (the_styles.appendTo('head'), the_styles=null) : the_styles = $('.stylesheet').detach();
Here's what the Mozilla Developer Center writes about the comma operator:
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple parameters in a for loop.
Read more here: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator
Who needs the ternary operator?
​the_styles = !the_styles && $('.stylesheet').detach()​​​​ ||
the_styles.appendTo('head') && null;​
Had to switch the expressions around as otherwise the null value of the first expression will always force the second expression .detach() to be evaluated.
The only thing about clever code is that once you come back to it after a coffee break, it won't make any sense even to you. So this is much better:
if(the_styles) {
the_styles.appendTo('head')
the_styles = null;
}
else {
the_styles = the_styles.detach('.stylesheet');
}
To me, even the above simplistic version doesn't make any sense. The what part is obvious, but why is it doing that?
the_styles ? (function() {the_styles.appendTo('head'); the_styles=null})() : <etc>
Just wrap the code block in (function() { and })().
Now for the hard part: why would you want to do this? Perhaps there's a better solution!
i agree with glowcoder but if you still want it:
the_styles ? function(){ the_styles.appendTo('head'); the_styles=null;}() : the_styles = $('.stylesheet').detach();
the_styles ? the_styles.appendTo('head') : the_styles = $('.stylesheet').detach();
you dont need to null it if your overwriting it !
the_styles=the_styles || $('.stylesheet').detach(); the_styles.appendTo('head');

Categories

Resources