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?
CodePudding user response:
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.
CodePudding user response:
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.