score:30
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.
score:-1
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>
score:0
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.
score:1
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';
}
score:1
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.
score:1
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.
score:1
multiple condition in ternary operator in jsx
and js
style={{'backgroundcolor': status === 'approved' ? 'blue' : status === 'cancel' ? 'red' : 'green'}}
score:3
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.
score:24
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>
);
}
Source: stackoverflow.com
Related Query
- multiple condition in ternary operator in jsx
- Multiple condition in ternary operator in jsx my component not showing
- ternary operator in jsx to include html with react
- Can I render multiple element in a ternary condition without else?
- Why is ternary operator in jsx not working
- How to use ternary operator within the jsx of a react component along with typescript?
- Why does ternary operator work and others don't in React JSX
- Render a React Component Using Multiple Ternary Operator
- How to use ternary operator to return jsx using react?
- Rendering multiple conditions ternary operator in React
- and condition in ternary operator not working
- Unable to Embed redirect using Ternary operator in JSX
- How to use ternary operator for rendering jsx using react?
- insert or remove enclosing element based on ternary operator JSX
- ternary operator not rendering markup in react jsx
- Render multiple components with a single ternary operator
- How can I do a ternary operator inside a map with the mapping for the true condition but without the mapping for the false
- How can call multiple function in React ternary if else condition
- Ternary Operator in JSX - Alternative?
- ternary operator check return 0 while checking jsx react js
- how to convert multiple else if statements to ternary operator
- How to use OR Condition in Ternary operator in ReactJS
- Add function call inside ternary operator in JSX
- What to return in ternary operator in React's JSX when want to return nothing?
- Using multiple conditions in ternary operator to stop rendering component on specific routs
- How to use ternary operator for returning jsx using react and typescript?
- multiple expressions in ternary operator with react route
- Add ternary operator instead condition
- React ternary operator return jsx and string returns an Object
- Why ternary operator in JS with multiple statements is not working?
More Query from same tag
- React-redux map error TypeError: Cannot read property 'map' of undefined
- [react-router v4]Do I get to read parent params in a nested Routes pattern?
- State message in react not printing to browser correctly
- React-native, use fullscreen image on android
- How socket.io can be used like axios?
- How to add JSX inside props?
- How to link sort function from header icon to the column to be sorted in React
- Full Screen Component ReactJS
- Rendering random elements from an array in React
- How to solve TypeError: Cannot read properties of undefined (reading '0') in Reactjs?
- Can't connect Google Calendar to Fullcalendar in React/Nextjs
- Apply a function to every single React Component
- Materia UI simple select not saving selection
- Viewing a single post with mongodb in react.js
- ref.current is null in react
- Module not found: Can't resolve './containers'
- React Hook "useParams" is called in function "fetchMentors" that is neither a React function component nor a custom React Hook function
- How to parse a boolean from a JSON response in React
- How to convert a container having three rows and three column into four rows and two columns
- Can a React selector return a specific type?
- @material-ui Autocomplete: set input value programmatically
- Type Error when destructuring elements In ReactJS
- How can I include URL params when programmatically navigating using the history API (not Links)?
- this.setState() not working properly with bound events
- With React Semantic UI use NavLink to set active page class?
- Django: Unsupported media type
- Email validation is not working correctly - don't know why it's not running properly
- Hookrouter (react) changes url but not the view, only after refreshing the page by yourself
- [Error]_Cannot find module 'babel-preset-es2015'
- Form does not submit default value of Material UI DateTimePicker