John John - 13 days ago 8x
React JSX Question

Conditional attributes in React component?

I'm new to react and I just wrote some ugly code. Can someone show me the better way to do it? Here's the pseudocode:

let btn;

if(this.props.href && !this.props.onClick && !this.props.dataMsg etc...)
btn = <a href={this.props.href}>{this.props.text}</a>;

else if(!this.props.href && this.props.onClick && !this.props.dataMsg etc...)
btn = <a onClick={this.props.onClick}>{this.props.text}</a>;


else if(this.props.href && this.props.onClick && !this.props.dataMsg etc...)
btn = <a href={this.props.href} onClick={this.props.onClick}>{this.props.text}</a>;

else if(!this.props.href && this.props.onClick && this.props.dataMsg etc...)
btn = <a onClick={this.props.onClick} data-msg={this.props.dataMsg}>{this.props.text}</a>;


In other words, I want to set the attributes of the
element only if the react component received a props for it. However, not all props of the react component are meant to be an attribute, some of it could be
which belongs in the innerHTML.

There must be a less verbose way to write what I want?


React will ignore all the attribute which has undefined as its value.

So, you don't need to use if conditions. Instead, you can check for the value attribute and return undefined if you don't get the value.

For Example:

You can write you code as follows,

  href={this.props.href} //returns undefined if href not present in props
  onClick={this.props.onClick && this.props.onClick} //set callback if it is present in the props
  data-msg={this.props.dataMsg} //returns undefined if href not present in props

Returning undefined to any attributes makes React to ignore those attributes.

Hope it helps!