Reputation: 48
Currently, in my React app I have this,
<input style={{ borderColor: valid ? null : "red", boxShadow: valid ? null : "rgb(2, 0, 0)"}} />
If I have more styling to do, it doesn't make sense checking the same condition again and again right? I wish to make the entire style attribute optional; something like this,
<input valid ? null : style={{ borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
But I know that's not the right syntax. Isn't there a better way to do this?
Upvotes: 3
Views: 2337
Reputation: 75
One option would be to create a variable:
const inputStyle = !valid ? {
borderColor: "red",
boxShadow: "rgb(2, 0, 0)"
} : {};
<input style={inputStyle}/>
It is the same that you currently have but you can add new properties as you wish into the variable without increasing the amount of comparisons in the input
tag.
Upvotes: 2
Reputation: 13933
You should use className to add style classes conditionally.You can use the classnames package as answered to the question
Upvotes: 3
Reputation: 728
You need to put the logic into the style attribute and pass a neutral element for it in case of valid (or extract it into a variable). I think this should do the trick:
<input style={valid ? {} : { borderColor: "red", boxShadow: "rgb(2, 0, 0)"}} />
Upvotes: 2
Reputation: 5283
You can define your styles as an object in the render method, then assign it optionally as prop to the component using ternary and spread operators.
const styles = {
borderColor: "red",
boxShadow: "rgb(2, 0, 0)",
// etc...
};
return (
<input { ...(valid ? { styles } : {}) } />
);
Upvotes: 2