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 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, it does work. I just didn't want to get a new package. Thanks!
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)"}} />

1 Comment

Yeah. This works the best for me, without having to create any extra variables and add any packages. Thanks!
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 } : {}) } />
);

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.