multiple condition in ternary operator in jsx - javascript

<div style={{'backgroundColor': status === 'approved' ? 'blue' : 'black'}}>
</div>
black is the default color but what if I want to add the 3rd condition?
status can be 'approved', 'rejected', 'pending' or more.

You could do the following:
<div style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'pending' ? 'black' : 'red'}}>
</div>
This means if status === 'approved' set the background color as blue, if status === 'pending' set it as black, else set it as red.

I would suggest using functions if your conditions get complicated, to not degrade your code readability.
getBackgroundColor(status) {
if (status === 'approved') {
return 'blue';
}
if (status === 'pending') {
return 'red';
}
return 'black';
}
render() {
// ...
return (
<div style={{ 'backgroundColor': this.getBackgroundColor(status) }}></div>
);
}

To chain ternary operations you need to add another ternary operator to be returned when the conditions are not met, for example:
a === true ? a : b
In place of b you would add a new ternary operator, like so:
a === true ? a : b === true ? b : c
Bonus:
When you're just checking for null/undefined/false you can use the pipe operator, for example this:
var x = a !== null ? a : b;
Can be simplified to:
var x = a || b;
And pipe operators can be chained infinitely like ternary operators.

There is another way how to do it with the a bit more readable & cleaner code style. We can replace the ternary operator with the object literal and use this instead of nesting ternary operators, like so
function getBackgroundColor(status){
const backgroundColorByStatus = {
approved: 'blue',
pending: 'black',
default: 'red',
}
return backgroundColorByStatus[status] || backgroundColorByStatus['default']
}
// somewhere below
<div style={{'backgroundColor': getBackgroundColor(status)}}>fancy div</div>
With this approach you can have multiple colors and code will be still clean & readable :)
Hope it will help.

Multiple condition in ternary operator in JSX and JS
style={{'backgroundColor': status === 'approved' ? 'blue' : status === 'cancel' ? 'red' : 'green'}}

Using multiple ternary operators is not a good idea, better to use a function and put if-else conditions inside that and call that function from render. It helps you to make the render part clean and short.
Like this:
<div style={{'backgroundColor': this._style(status)}}></div>
_style(status){
if(status == 'approved')
return 'blue';
else if(status == 'pending')
return 'black';
else return 'red';
}

I'd handle it separately as other types of status may appear in the future.
const getBackgroundColor(status) {
if (status === 'approved') {
return 'blue'
}
else if (status === 'pending') {
return 'black'
} else {
return 'red'
}
}
<div style={{'backgroundColor': getBackgroundColor(status) }}>
</div>
Code gets easier to understand and reason about.

I would not use ternary because it gets hard to read. Why not store the status and associated colors in an object then just reference that?
const colors = {approved:"blue", rejected:"red"};
<div style={{'backgroundColor':status in colors ? colors[status] : "black"}}>
</div>
Oops, I didn't realize how old this thread was.

Inside render you can create an empty array variable. As shown below, you can apply nested styling. Also, you won't need a nested ternary operator.
let styleValue = [];
if(status === 'approved') {
styleValue.push({backgroundColor:'blue'})
} else {
styleValue.push({backgroundColor:'black'})
}
<div style={styleValue}>
</div>

Related

Multiple conditions/operators to show/hide html elements in React (NextJS)

I'm looking to display some html in my React/Next.js web app based on conditional logic. I got the basics working but having issues showing the same html if multiple variable conditions are true. For example, the following code works fine.
{category === 'ford' &&
<div>Car</div>
}
{category === 'harley' &&
<div>Motorcycle</div>
}
I'm having issues showing multiple variables as true. The following code doesn't work but show the logic I'm after.
{category === 'ford' || category === 'toyota' &&
<div>Car</div>
}
//this code doesn't work.
I realise a simple answer is to separate operators for each separate condition, however i'm trying to avoid duplicating the html <div>Car</div> (as in my actual application contains large forms in this section).
You will need to wrap the OR-Condition in parentheses like so:
(category === 'ford' || category === 'toyota') && <div>Car</div>
you can also make use of Array includes method
I would make an array for e.g.
const cars = ["honda", "toyota", ....];
const motorcycle = ["euler", "ducati", ...];
{cars.includes(category) ? <div> cars </div> : <div> motorcycles </div> }
const isCarCategory = ["ford", "toyota"].includes(category);
const isMotorcycleCategory = ["harley"].includes(category);
return (
<div>
{isCarCategory && <div>Car</div>}
{isMotorcycleCategory && <div>Motorcycle</div>}
</div>
);
Just wrap your condition inside parenthesis.
Parenthesis must be used, if multiple conditions needs to be checked.
Check this link about Precedence And Associativity https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
{(category === 'ford' || category === 'toyota') &&
<div>Car</div>
}
you can wrap it all in a different function and use a switch statement (or arrays) to handle not managed category
like this
const renderVehicle = (category) => {
switch(category) {
case 'honda':
case 'ford':
return <div>Car</div>
case 'harley':
return <div>Motorcycle</div>
default:
return <div>Not found</div>
}
}
const renderVehicle2 = (category) => {
const cars = ['honda', 'ford']
const motorcycles = ['harley']
if(cars.includes(category)){
return <div>Car</div>
}
if(motorcycles.includes(category)){
return <div>Motorcycle</div>
}
return <div>Not found</div>
}
the simple answer is to wrap the condition in ()
{(category === 'ford' || category === 'toyota') &&
<div>Car</div>
}

javascript - if is not getting triggered when it should

I have this little snippet of code
<Calendar
style={{ height: 600, width: "120%" }}
eventPropGetter={(event, start, end, isSelected) => {
var backgroundColor = "#000000";
console.log(event.estado);
console.log(isSelected);
if (event.estado === 0 && isSelected === false)
console.log("here");
if (event.estado === 0 && isSelected === true)
backgroundColor = "#4d4dff";
if (event.estado === 2 && isSelected === true)
backgroundColor = "#ff8c1a";
if (event.estado === 2 && isSelected === false)
backgroundColor = "#b35900";
return { style: { backgroundColor } };
}}
console.log(event.estado) spits out 0
console.log(isSelected) spits out false
however, console.log("here") is never triggered. As I'm new to JS, I'm assuming there's some quirkiness in how JS evaluates truthiness that I'm not aware about
Any help would be appreciated
The 0 was in fact "0", that's why it was evalutaing wrong
As per html doc below, type and value should be same. Please check whether type of isSelected is same.
When using the === operator, equal booleans are not equal, because the === operator expects equality in both type and value
I tried the snippet on my end and it worked for me perfectly and is printing here (I didn't use console log though). Can you once try to equate estado to 1 and check if the background changes!!

javascript elseif case in JSX

Hi when I have a condition output in frontend is there a possibility to make a else if () statement as well?
current code looks like:
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
}
Thanks in advance
You can use the conditional operator to make if/else expressions:
{someCondition === true ? (
<TrueComponent/>
) : (
<FalseComponent/>
)}
If you want an if/elseif/else, you can combine multiple conditionals together:
{someCondition === true ? (
<IfComponent/>
) : someOtherCondition === true ? (
<ElseIfComponent/>
) : (
<ElseComponent/>
)}
These things can be difficult to read, so you should consider pulling this code up above your return statement, using normal if's and elses:
let component;
if (someCondition === true) {
component = <IfComponent/>
} else if (someOtherCondition === true) {
component = <ElseIfComponent/>
} else {
component = <ElseComponent/>
}
return (
<div>{component}</div>
);
{this.props.contentComponentData.typeOf === 1
&&
<ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
|| condition && ifConditionMetExpression
}
But this is a bit hard to read, I suggest you use ternaries instead:
{this.props.contentComponentData.typeOf === 1
? <ContentComponentChecklistInstances
checklistItems={this.props.contentComponentData.checklists}
/>
: condition
? ifConditionMetExpression
: null
}
(first condition)
? // if first condition true this part run
: (second condition)
? // if second condition true this part run
: // else part

how to setup the class name in my case

I am trying to combine the ng-class condition statements in my case.
I have the following statements.
<div ng-class="item.new ? 'newItem' : 'oldItem'; 'discount' : item.getType === true && item.getSave === true">{{item.name}}</div>
I am getting the parsing error.
Syntax Error: Token ':' is an unexpected
I am not sure how to fix this. Can anyone help me about it? Thanks a lot
Use this syntax instead:
<div ng-class="{newItem: item.new, oldItem: !item.new, discount: item.getType === true && item.getSave === true}">
Or alternatively put your logic in a function:
<div ng-class="getClasses(item)">
And in your controller:
$scope.getClasses = function(item) {
return {
newItem: item.new,
oldItem: !item.new,
discount: item.getType === true && item.getSave === true
};
}
FYI: from that function you can return an object, or an array of classes, or a string.

Is there an alternative to using IF / ELSE statements

Question
More out of curiosity, but I was wondering how to refactor an if statement to something cleaner / less brittle. From what I have read, polymorphism could have a use?
In the example I only want to return the first car if color:'red' is true.
Coffeescript
example: () ->
cars = [{color:'red', reg:'111'},{color:'blue', reg:'666'}]
if cars[0].color is 'red'
then cars[0]
else cars[1]
Javascript
example: function() {
var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
if (cars[0].color === 'red') {
return cars[0];
} else {
return cars[1];
}
}
I understand this question maybe closed or moved due to the ambiguous nature
? : operator is exactly that, a "cleaner" if-else
http://msdn.microsoft.com/en-us/library/ty67wk28.aspx
classify = (input < 0) ? "negative" : "positive";
There are also switch statements for larger combinations:
http://www.w3schools.com/js/js_switch.asp
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Polymorphism is an abstract concept, not a way to write a statement. It's the practice of creating a method/function/class/etc where type is at least SOMEWHAT ambiguous. So the same method could return a result if fed, say, an integer for parameter 1, the same as if you were to feed an array into the same parameter.
You can use ternary operator, its syntax is condition ? result1 : result2;
return cars[0].color === 'red' ? colors[0] : colors[1]
Just for fun :
// red -> +false -> 0
// not red -> +true -> 1
return cars[+(cars[0].color !== 'red')];
Turning Car into an object:
function Car(options) {
this.options = {};
// Some default options for your object
$.extend(this.options, {
color: "green",
buildYear: 1990,
tires: 4,
brand: "merceded"
}, options);
}
// A method registered on the prototype
Car.prototype.getColor = function () {
return this.options.color;
};
var myToyota = new Car({
brand: "toyota"
});
console.log("My Toyota is: "+ myToyota.getColor());
example: http://jsfiddle.net/YthH8/
Keep in mind that are are many ways you can use objects / inheritance in JavaScript.
Coffee script has it's own syntactic sugar for using classes => http://coffeescript.org/#classes
There is a ternar operator ? used mostly when you don't want to use if-else statement:
example: function() {
var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
return cars[0].color === 'red' ? cars[0] : cars[1];
}
const example = () => {
var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
return (cars[0].color === 'red' && cars[0]) ||
cars[1];
}

Categories