3

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?

4 Answers4

3

You should use className to add style classes conditionally.You can use the classnames package as answered to the question

DevLoverUmar
  • 11,809
  • 11
  • 68
  • 98
2

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)"}} />
Benjamin Eckardt
  • 709
  • 6
  • 10
2

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.

2

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 } : {}) } />
);
M0nst3R
  • 5,186
  • 1
  • 23
  • 36