Karthik G M
Karthik G M

Reputation: 48

Can I add optional attributes to an element in React?

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

Answers (4)

Gustavo
Gustavo

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

DevLoverUmar
DevLoverUmar

Reputation: 13933

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

Upvotes: 3

Benjamin Eckardt
Benjamin Eckardt

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

M0nst3R
M0nst3R

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

Related Questions