Conditionally add attributes to React components
In this article, we will show you how to conditionally add attributes to React components. There are multiple ways to dynamically add attributes to a React element but we will show you the best way out of them.
Checkout more articles on ReactJS
Create an object the way you like.
1 2 3 4 5 6 7 | var inputProps = { cols: "50", onChange: this.handleChange }; if (condition) inputProps.rows = "4"; |
Render with a Spread Operator, optionally passing other props also.
1 2 3 4 | <textarea name="cluemediator" {...inputProps} /> |
This approach is actually very useful, especially when adding many properties conditionally.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂