Conditional statements in line in React.js (jsx)

Viewed 143

I'm got a React application where I'm using JSX and I have a condition that is: if an input is selected (i.e. is true) pass a particular query through to a search engine. I also want to add background styling to the same condition so I came up with the following:

<div style={ui.selected.thisInput && {background: "red"} }></div>

I also tried:

<div style={{ ui.selected.thisInput ? "background:red" }}></div>

Both of which throw errors.

2 Answers

You can do:

<div {...(condition ? { style: { background: 'red' } } : {})}></div>

or

<div style={condition ? { background: 'red' } : {}}></div>

As the current one in question:

<div style={condition && { background: 'red' }}></div> // Wrong

will produce the correct style when condition is true but will produce wrong style i.e. style={false} when condition is false.

try this

<div style={{ background:condition?"red":"blue"}}>

OR

<div style={{ background:condition?"red":""}}>

example

Related