Reputation: 19
class App extends React.Component {
render() {
return (
<div className="bg">
{productList.map((product) => {
return (
<div className="mainContainer">
<div className="billedeContainer">
<img src={product.image} />
</div>
<div className="titel">Vare: {product.title}</div>
<div className="type">Type: {product.type}</div>
<div className="producent">Producent: {product.producer}</div>
<div className="unit">
{product.unitSize} {product.unit}
</div>
<div className="kolli">
Kolli mængde: {product.price * product.bulkSize}
</div>
<div>Antal: {product.quantity}</div>
<div className="prisContainer">
<div className="pris">{product.price} kr,-</div>
</div>
</div>
);
})}
</div>
);
}
}
I want to make an if statement on div "type", but I can't get the syntax to work properly. I am new at react/jsx.
I want an if that says, whenever "type" is null in my array, then there shouldn't be an "type" appearing.
Upvotes: 2
Views: 2215
Reputation: 1074555
You can use a JSX expression to do that. If the expression evaluates to null
, undefined
, or false
, nothing at all is shown where the expression appears.
You said your product.type
may be null
, so you can use the curiously-powerful &&
operator:
{product.type && <div className="type">Type: {product.type}</div>}
The {}
is the JSX expression. The &&
operator works like this: It evaluates its left-hand operand and, if that value is falsy,¹ takes the value as its result, completely ignoring the right-hand operand. If the left-hand operand's value is truthy, the expression evaluates the right-hand operand and takes that value as its result.
So if product.type
is null
, {product.type && <Stuff />}
is {null}
and nothing gets rendered. If product.type
isn't null
, {product.type && <Stuff />}
results in {<Stuff />}
.
If you were testing something that might be 0
or some such, you wouldn't use &&
because you'd end up with a 0
in the rendered output (since only null
, undefined
, and false
are ignored). In that case you'd use a conditional expression:
{mightBeZero ? <Stuff /> : null}
¹ A falsy value is any value that's treated as false
in a condition. The falsy values are 0
, null
, undefined
, NaN
, ""
, and of course, false
. All other values are truthy.
Upvotes: 2
Reputation: 1144
<div className="type">Type: {product.type}</div>
=> {product.type ? (<div className="type">Type: {product.type}</div>) : null }
or
`{product.type && (<div className="type">Type: {product.type}</div>)}`
Upvotes: -1
Reputation: 41
You can use conditional statements in render.
item && item.type? Show type: null
But better is to place the code in seperate function if it is too complex.
Upvotes: -1
Reputation: 1961
Let try, when type is null, Type div will not be rendered:
{product.type && <div className="type">Type: {product.type}</div>}
Upvotes: 2