Clue Mediator

Conditionally add attributes to React components

πŸ“…December 6, 2021
πŸ—ReactJS

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.

var inputProps = {
  cols: "50",
  onChange: this.handleChange
};

if (condition)
  inputProps.rows = "4";

Render with a Spread Operator, optionally passing other props also.

<textarea name="cluemediator" {...inputprops}=""></pre><p></p><p>This approach is actually very useful, especially when adding many properties conditionally.</p>
<p>I hope you find this article helpful.<br />Thank you for reading. Happy Coding..!! πŸ™‚</p>
<!-- /wp:html --></textarea>