Reputation: 319
<Link style={!id && {'cursor':'normal'}}>link</Link>
Anything wrong with my above jsx expression? trying to add a style if id is not defined.
Upvotes: 0
Views: 1361
Reputation: 1074038
Sadly, the documentation doesn't discuss this.
But empirically, no, you can't do it like that because when there is an id
, you'll end up with style={false}
, which React doesn't like (it complains that "The style
prop expects a mapping from style properties to values, not a string." even though false
isn't a string).
Empirically, using either null
or undefined
works, which means either the conditional operator:
style={id ? null : {cursor: "normal"})
Example:
const Foo = props => <div style={props.id ? null : {color: "green"}}>Testing</div>;
ReactDOM.render(
<div>
<Foo id="a" />
<Foo />
</div>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
...or adding ||
, which is fairly ugly:
style={!id && {cursor: "normal"} || null}
Example:
const Foo = props => <div style={!props.id && {color: "green"} || null}>Testing</div>;
ReactDOM.render(
<div>
<Foo id="a" />
<Foo />
</div>,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
Upvotes: 3
Reputation: 41893
Use ternary operator.
<Link style={!id ? { cursor:'normal' } : null}>link</Link>
Upvotes: 4